定制特性(Attribute)
一.认识定制特性
1..net定制特性的作用在于:自定义的定制属性可以用于于几乎所有的元数据表项上,然后在运行时通过查询这些可扩展的元数据信息来动态的改变代码的执行方式。
2.定制特性其实是一个以Attribute结尾的类的实例,类继承自System.Attribute,它可以作用于:程序集,模块,类型,字段,方法,属性,方法参数,方法返回值,委托,接口等。
3.有一个叫AttributeUsageAttribute的类,它用来限制自定义定制属性的修饰范围,它的构造器有2个参数:AttributeTargets参数(枚举类型),Inherited(bool类型),前者指定了定制属性可以修饰的目标(如All表所有,class表类,Assembly表程序集等),后者表示是否继承(true则继承),即如果此定制属性用在父类上Base上,子类Derived是否可以继承此属性(或者方法的Override是否也继承)。
如: [AttributeUsage(AttributeTargets.Enum,Inherited=false)]
public class FlagsAttribute : Attribute
{
public FlagsAttribute(){ }
}
FlagsAttribute只能运用在Enum类型上
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,Inherited=true)]
class TastyAttribute : Attribute{ }
[Tasty]
[Serializable]
public class SomeType
{
[Tasty]
public virtual void DoSomething()
{
}
}
public class AnotherType:SomeType
{
public override void DoSomething()
{
}
}
Tasty定制属性可以用在class或method上,能够支持集成,那么对于子类AnotherType可以继承Tasty属性(但不能继承Serialize属性,它不支持继承),AnotherType的DoSomething()也继承了Tasty属性。
4.定制属性运用在目标上时,用[]表示,可以不写后缀Attribute,()中,出现在构造器的参数必须赋值,其他的属性可选,用”,”分隔,实际上[***]操作就相当于执行定制属性构造器。
二.检测定制特性
定制特性的检测有2种途径,一是通过目标类型的方法(如Type或Assembly或Method等的IsDefined(),GetcustomAttributes()等),二是通过Attribute的方法,如IsDefined(),GetcustomAttributes()等。
如: SomeType someType = new SomeType();
Type tp = someType.GetType();
tp.IsDefined(typeof(TastyAttribute), true);
tp.IsDefined将返回true,因为someType上运用了TastyAttribute属性,IsDefined方法的bool参数表示是否在继承关系中(如父类)查找指定的定制属性。
Type的GetcustomAttributes()返回object[],而Attribute的GetcustomAttributes()返回Attribute[].
GetcustomAttribute()返回一个指定的运用在目标元素上的定制属性实例,
GetcustomAttributes()返回所有运用在目标元素的定制属性实例。它们都有多种重载形式,具体可查阅MSDN.