特性 Attribute

特性就是一个类,必须是Attribute的子类

一般以Attribute结尾,然后在使用的时候,可以去掉这个结尾

可以在特性中声明字段、属性、方法、构造函数、委托、事件...

    [AttributeUsage (AttributeTargets.All ,AllowMultiple =true )] //这样这个属性可以重复在一个类上使用
    class CustomAttribute:Attribute 
    {
        public CustomAttribute ()
        {

        }
        private string _Remark = "";
        public CustomAttribute (string remark)
        {
            this._Remark = remark;
        }

        public string Description { get; set; }

        public int Id;

        public void Log()
        {
            Console.WriteLine(this._Remark);
        }

        public delegate void DoDelegate();
        public event DoDelegate DoEvent;
    }
[Custom] //调用无参数的构造函数
[CustomAttribute()] //调用无参数的构造函数
[CustomAttribute("这里是我的测试")]//调用有参数的构造函数
[CustomAttribute("这里是Remark的",Description= "这里是Description")]//调用有参构造函数,给属性赋值
[CustomAttribute(Description = "这里是Description")]//调用无参构造函数,给属性赋值

 

特性可以影响编译,也可以影响运行

特性会被编译到matedata(exe或dll文件包含IL和metadata),metadata数据只能通过反射获取

通过特性,在不侵入原类型的情况,给对象增加了额外的行为

具体看代码

 

posted @ 2016-12-26 16:41  HepburnXiao  阅读(180)  评论(0编辑  收藏  举报