C# 中的反射

2023年 8月 29日 96.1k 0

C# 中的反射

反射对象用于在运行时获取类型信息。允许访问正在运行的程序的元数据的类位于 System.Reflection 命名空间中。

以下是 Reflections 的应用 -

  • 它允许在运行时查看属性信息。

  • 它允许检查程序集中的各种类型并实例化这些类型。

  • 它允许后期绑定到方法和属性
  • 它允许在运行时创建新类型,然后使用这些类型执行一些任务。

  • ul>

    让我们看一个例子 -

    示例

    using System;

    [AttributeUsage(AttributeTargets.All)]
    public class HelpAttribute : System.Attribute {
    public readonly string Url;

    public string Topic // Topic is a named parameter {
    get {
    return topic;
    }
    set {
    topic = value;
    }
    }
    public HelpAttribute(string url) // url is a positional parameter {
    this.Url = url;
    }
    private string topic;
    }

    [HelpAttribute("Information on the class MyClass")]
    class MyClass {
    }

    namespace AttributeAppl {
    class Program {
    static void Main(string[] args) {
    System.Reflection.MemberInfo info = typeof(MyClass);
    object[] attributes = info.GetCustomAttributes(true);

    for (int i = 0; i < attributes.Length; i++) {
    System.Console.WriteLine(attributes[i]);
    }
    Console.ReadKey();
    }
    }
    }

    登录后复制

    以上就是C# 中的反射的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论