c#特性简述使用

来源:互联网 发布:java脱壳工具 编辑:程序博客网 时间:2024/06/06 17:07
什么是特性?

定义:特性本质上也是有一种类,通过添加特性,就可以实例化这个特性类;

直接进入正题,特性大致可以分为两种:
一:系统自带的特性
二:自定义特性

我们主要讲一下如何自定义特性,定义的方式和普通的类定义方式一致,但是,
第一:需要继承标准特性类
第二:需要添加标准特性,用来限制特性的使用范围等
第三:必须要定义构造函数,即使是空的
如下:
[AttributeUsage(AttributeTargets.All,AllowMultiple = true, Inherited=true)]  //基于标准特性class CustomAttr:Attribute                                                   //继承标准特性类{    //0参数构造函数    public CustomAttr()    {    }    
   //3个参数构造函数
public CustomAttr(string name, int sore,string message) { this.name = name; this.sore = sore; this.message = message; } public string name { get; set; } public int sore { get; set; } public string message { get; set; }}
使用特性例子如下:(这里相当于实例化了2个类)
[CustomAttr(name ="dj",sore=100,message ="222")][CustomAttr(name = "sq", sore = 100, message = "666")]class Test{}


注意:

[CustomAttr(name ="dj",sore=100,message ="222")],  这里相当于调用了不带任何参数的构造函数,但是使用属性功能进行赋值

[CustomAttr("dj,100,"666")],                                              这里相当于直接调用了带有三个参数的构造函数

这就是为什么我们必须要给自定义特性类添加构造函数的原因


实测:
static void Main(string[] args){    System.Reflection.MemberInfo info = typeof(Test);    var customAttrLsit = Attribute.GetCustomAttributes(info, typeof(CustomAttr)) as CustomAttr[];    for (int i = 0; i < customAttrLsit.Count(); i++)    {        Console.WriteLine("================================================");        Console.WriteLine("创建人:{0}", customAttrLsit[i].name);        Console.WriteLine("创建时间:{0}", customAttrLsit[i].sore);        Console.WriteLine("备注消息:{0}", customAttrLsit[i].message);    }    Console.ReadKey();}

使用特性可以方便的为我们给类和方法加上从元数据!