特性(Attribute)的使用

为了便于与类中属性( property)的区分,如下Attribute都统称为特性。
特性出现的形式:一种是在公共语言运行库,另外一种是本身定义的特性。主要用于向代码中添加附加消息的自定义特性。
特性的特色:
1 属性可向程序中添加元数据。元数据是嵌入程序中的信息,如编译器指令或数据描述。
2 程序能够使用反射检查本身的元数据。
3 一般使用属性与  COM  交互。
特性该怎么实现呢?
方法:特性类实例化时须要放在括号“ [ ]” 中,语法:
       [attributeClass( 定位参数 1 …  命名参数 1,…)]
定位参数和命名参数稍有不一样,定位参数为构造函数中的参数,命名参数为其余的属性字段。参数的类型有如下几种:
1 基本数据类型中的值类型:×××,浮点类型,字符,  Bool
2 System.object, System.Type,System.string
3 )枚举类型
4 以上任何类型的一维数组
凡是不符合以上几种的都是错误的特性定义。
定义自定义特性的方式:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,AllowMultiple=true ,Inherited =true ) ] //Author 特性性只能用于类和结构, AllowMultiple 是否容许屡次使用特性, Inherited 是否容许继承
public class AuthorAttribute : Attribute //此处必须继承自Attribute
 {
   private string name; 
   public double version;  //此为命名参数
   public AuthorAttribute(string name) //构造函数定义的参数为定位参数。
    {
     this.name = name; version = 1.0;
    }
        public string Name
       {
           get{return name;}
       }
 }
[Author(“ 张三 ”, version =2.0)]// 张三是 Author 的构造函数的参数, version 是字段,字段必须写出字段名。
 class SampleClass
 {  }
以上就完成了特性的定义。
怎么经过反射获取特性中的字段呢,这是个颇有用的用法。
首先经过 Typeof方法得到使用特性类的类型
Type ty = typeof( SampleClass );
而后用反射就能够获取特性所传递的值了
((AuthorAttribute)(ty.GetCustomAttributes(false)[ 0 ])).name
这样,就能够打印或者调用了。
相关文章
相关标签/搜索