C#高级编程——Reflection反射
反射就像在主程式里面,安装了一个声纳探测器,
在生命周期一开始的时候,就会调用探测器,你的方法执行依赖于声纳反射回来的声波,
这样的做的好处是,当你想更新程序的时候,只需要加dll就行了,
不需要重新编译。
这样,就成了插件式的编程。
实例:
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
public string Topic // Topic 是一个命名(named)参数
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url) // url 是一个定位(positional)参数
{
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
参考文档:
Today's comments have reached the limit. If you want to comment, please wait until tomorrow (UTC-Time).
There is 04h21m14s left until you can comment.