Attribute 是什么
Attribute 是一种可由用户自由定义的修饰符(Modifier),可以用来修饰各种需要被修饰的目标。
简单的说,Attribute就是一种“附着物” —— 就像牡蛎吸附在船底或礁石上一样。
这些附着物的作用是为它们的附着体追加上一些额外的信息(这些信息就保存在附着物的体内)—— 比如“这个类是我写的”或者“这个函数以前出过问题”等等。
Attribute 的作用
特性Attribute 的作用是添加元数据。 元数据可以被工具支持,比如:编译器用元数据来辅助编译,调试器用元数据来调试程序。
Attribute 与注释的区别
- 注释是对程序源代码的一种说明,主要目的是给人看的,在程序被编译的时候会被编译器所丢弃,因此,它丝毫不会影响到程序的执行。
- 而Attribute是程序代码的一部分,不但不会被编译器丢弃,而且还会被编译器编译进程序集(Assembly)的元数据(Metadata)里,在程序运行的时候,你随时可以从元数据里提取出这些附加信息来决策程序的运行。
Attribute 的本质
Attribute 本质上就是一个类,它在所附着的目标对象上最终实例化。
仔细观察中间语言(MSIL)的代码之后,那些被C# 语言所掩盖的事实,在中间语言(MSIL)中就变得赤身裸体了。而Attribute 也变得毫无秘密!
图中红色所指的是Fun 方法及其修饰符,但Attribute 并没有出现在这里。
图中蓝色所指的是在调用mscorlib.dll 程序集中System.Diagnostics 名称空间中ConditionalAttribute 类的构造函数。
可见,Attribute 并不是修饰符,而是一个有着独特实例化形式的类!
Attribute默认值为
AttributeTargets.All 该属性指定我们的自定义attribute可以放置在哪些语言元素之上
AllowMultiple=false 该属性标识我们的自定义attribte能在同一语言元素上使用多次
Inherited=true 该属性标识我们的自定义attribute是否可以由派生类继承
public class HelpAttribute : Attribute { protected string description; protected string version; public HelpAttribute(string Description) { this.description = Description; this.version = "1.0"; } public string Description { get { return this.description; } } public string Version { get { return this.version; } set { this.version = value; } } } [Help("First Attribute")] public class Hong { } [Help("First Attribute Hongda",Version="3.3")] public class Hongda : Hong { } class Program { static void Main() { Type type = typeof(Hongda); HelpAttribute HelpAttr; foreach (Attribute attr in type.GetCustomAttributes(true)) { HelpAttr = attr as HelpAttribute; if (HelpAttr != null) { Console.WriteLine("HelpAttribute Description:" + HelpAttr.Description + " Version:" + HelpAttr.Version); } } Console.Read(); } }
子类的Attribute覆盖了从父类继承的Attribute
public class Hong { [Help("Work")] public void Work() { } [Help("FF")] public string FF { get; set; } [Help("hon")] private string hon; }
反编译查看
属性
不加特性
数据成员
不加特性
[AttributeUsage(AttributeTargets.Parameter )] public class ParameterAttribute : Attribute { public ParameterAttribute(int size) { this.size = size; } private int size; public int Size { get { return size; } set { size = value; } } } public class Hong { public void work([Parameter(20)] string a,[Parameter(3)] int b) { } } class Program { static void Main() { Type type = typeof(Hong); ParameterAttribute ParameterAttr; foreach (MethodInfo method in type.GetMethods()) { foreach (ParameterInfo para in method.GetParameters()) { ParameterAttr = Attribute.GetCustomAttribute(para, typeof(ParameterAttribute)) as ParameterAttribute; if (ParameterAttr != null) { Console.WriteLine("Size:" + ParameterAttr.Size); } } } Console.Read(); } }
http://kb.cnblogs.com/page/87531/
http://sifang2004.cnblogs.com/archive/2006/01/12/316313.html
http://www.cnblogs.com/dc10101/archive/2009/03/24/1420199.html