C#特性本质

来源:互联网 发布:怎么成为起点网络作家 编辑:程序博客网 时间:2024/05/16 04:38
特性标签的本质
1、系统定义

2、自定义
1、特性标签本质上是一个类,此类建议写上Attribute后缀
2、特性标签类必须继承Attribute父类
3、类中的写法和普通类保持一致
注意点:在某个方法,字段,属性,类上面贴特性标签的时候,可以省略Attribute ,在中括号中使用

想要将自定义特性标签只能贴到class 应该加上:AttributeUsage(AttributeTargets.Class)
属性上:AttributeTargets.Property
字段:AttributeTargets.Felid
方法:AttributeTargets.Method

既想贴到方法又要贴到属性:AttributeTargets.Method | AttributeTargets.Property

Flag 枚举

AllowMultiple = true:表示允许贴多个特性标签

3、使用
特性标签一般是结合反射来进行使用的
3.1、如何判断一个类,方法,属性,字段上是否有贴Vip特性标签
类: Type->IsDefined(typeof(Vip特性标签名称)) ,如果有贴则返回true 否则 false
方法: MethodInfo ->IsDefined(typeof(Vip特性标签名称))
属性:PropertyInfo->IsDefined(typeof(Vip特性标签名称))
字段: FelidInfo->IsDefined(typeof(Vip特性标签名称))


3.2、获取类,方法,属性,字段上贴有的Vip特性标签
类:Type->GetCustomAttribute(typeof(Vip特性标签名称)) 如果有贴:返回的是Attribute 此时可以强制转换:Attribute as VipAttribute 
得到VipAttribute 的对象实例,相当于new VipAttribute()

方法: MethodInfo ->GetCustomAttribute
属性:PropertyInfo->GetCustomAttribute
字段: FelidInfo->GetCustomAttribute


GetCustomAttributes():表示获取当前类,方法,属性,字段上面的所有特性标签
GetCustomAttributes(Type attributeType):表示获取当前类,方法,属性,字段上面指定的所有特性标签

Inherited = true
表示:当前贴有此特性标签的类的子类也可以被继承使用
注意在使用的时候: 在IsDefined()或者GetCustomAttribute()或者 GetCustomAttributes() 这三个方法中,一定要加上inherit 的参数为true
否则没有用
例如:
        bool isok = type.IsDefined(typeof(VipAttribute), true);
不能如下写法
bool isok = type.IsDefined(typeof(VipAttribute), false);
0 1