C# 中的反射是什么?

csharpprogrammingserver side programming更新于 2025/10/14 8:07:17

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

需要初始化 System.Reflection 类的 MemberInfo 对象才能发现与类关联的属性。

在下面的示例中,我们设置了目标类的对象 −

System.Reflection.MemberInfo info = typeof(MyClass);

以下是示例 −

示例

using System;
using System.Reflection;

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

   public string Topic { // Topic 是一个命名参数
   get {
      return topic;
   }

   set {
      topic = value;
   }
}

public HelpAttribute(string url) { // url 是一个位置参数
   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();
      }
   }  
}

相关文章