特性(Attributes)

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

我们主要讲一下如何自定义特性,定义的方式和普通的类定义方式一致,但是,
第一:需要继承标准特性类
第二:需要添加标准特性,用来限制特性的使用范围等
第三:必须要定义构造函数,即使是空的
如下:

[AttributeUsage(AttributeTargets.All,AllowMultiple = true, Inherited=true)]  //基于标准特性
class CustomAttr:Attribute                                                   //继承标准特性类
{
    //0参数构造函数
    public CustomAttr()
    {
 
    }
 

使用特性例子如下:(这里相当于实例化了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();
}

 

posted @ 2016-11-25 15:53  在西天取经的路上……  阅读(372)  评论(0编辑  收藏  举报