.NET特性
无一列外特性也是一种对象,但是特性不同于其他对象,特性对象的作用是向程序集添加元数据,这也就意味着能够向编译器说明特性所作用的对象具有哪些特性,编译在通过这个特性得知这个对象在具备哪些特征(是否可以序列化等等)。特性就是起描述作用的,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。其描述的对象可以是程序集本身、模块、类、接口、结构、构造函数、方法、方法参数等。加载了特性的对象称作特性的目标。
在.NET下,特性是继承自Attribute,通过F12导航可以发现:1.Attribute其实是一个抽象类,其本身有被若干个特性所描述。其中最主要的是第二个AttributeUsage,顾名思义这个特性是用到描述特性的用途,其下有三个属性。对应着:特性所能描述的对象,是类,接口还是其他亦或者是所有类型都能描述。第二个指的是,当特性作用的类被继承是,其子类是否也同时继承了特性(如果某特性作用的类型不是类或者接口呢?)。AllowMultiple指的是改特性是否能重复作用于某个类型之上。
注意由于特性的定义其实就是给定义的该类生成一个对象,由于只有一行代码,从代码[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
可以得知对于构造函数的的参数是直接复制的,对于属性是用等号赋值的。
// 摘要:
// 表示自定义属性的基类。
[Serializable]
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Attribute))]
public abstract class Attribute : _Attribute
// 摘要:
// 指定另一属性类的用法。无法继承此类。
[Serializable]
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
[ComVisible(true)]
public sealed class AttributeUsageAttribute : Attribute
{
public AttributeUsageAttribute(AttributeTargets validOn);
public bool AllowMultiple { get; set; }
public bool Inherited { get; set; }
public AttributeTargets ValidOn { get; }
}