C# 中的反射

WBOY
发布: 2023-08-26 13:45:02
转载
1262 人浏览过

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# 中的反射的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!