C# 中的反射有哪些应用?
csharpprogrammingserver side programming更新于 2025/10/14 15:37:17
反射对象用于在运行时获取类型信息。允许访问正在运行的程序的元数据的类位于 System.Reflection 命名空间中。
以下是反射的应用 −
- 它允许在运行时查看属性信息。
- 它允许检查程序集中的各种类型并实例化这些类型。
- 它允许对方法和属性进行延迟绑定。
- 它允许在运行时创建新类型,然后使用这些类型执行某些任务。
System.Reflection 命名空间包含一些类,它们允许您获取有关应用程序的信息,并向应用程序动态添加类型、值和对象。
让我们再看一个例子。
下面我们设置了目标类的对象 −
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 {
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();
}
}
}
输出
HelpAttribute

