C#中的特性 和 通过反射获取属性上的特性

来源:互联网 发布:家里网络接线盒没连 编辑:程序博客网 时间:2024/04/30 12:00

1.了解类 AttributeUsage 

    AttributeUsage 有三个 属性 ,分别是 

         public bool AllowMultiple { get; set; }   作用:是否能在一个目标身上多次使用

         public bool Inherited { get; set; } 作用 :特性是否能继承到子类身上

         public AttributeTargets ValidOn { get; } 作用:设置特性的可使用范围

2.了解 AttributeTargets 枚举

 public enum AttributeTargets    {        // 摘要:        //     可以对程序集应用特性。        Assembly = 1,        //        // 摘要:        //     可以对模块应用特性。        Module = 2,        //        // 摘要:        //     可以对类应用特性。        Class = 4,        //        // 摘要:        //     可以对结构应用特性,即值类型。        Struct = 8,        //        // 摘要:        //     可以对枚举应用特性。        Enum = 16,        //        // 摘要:        //     可以对构造函数应用特性。        Constructor = 32,        //        // 摘要:        //     可以对方法应用特性。        Method = 64,        //        // 摘要:        //     可以对属性应用特性。        Property = 128,        //        // 摘要:        //     可以对字段应用特性。        Field = 256,        //        // 摘要:        //     可以对事件应用特性。        Event = 512,        //        // 摘要:        //     可以对接口应用特性。        Interface = 1024,        //        // 摘要:        //     可以对参数应用特性。        Parameter = 2048,        //        // 摘要:        //     可以对委托应用特性。        Delegate = 4096,        //        // 摘要:        //     可以对返回值应用特性。        ReturnValue = 8192,        //        // 摘要:        //     可以对泛型参数应用特性。        GenericParameter = 16384,        //        // 摘要:        //     可以对任何应用程序元素应用特性。        All = 32767,    }
3.自定义特性

  1.所有自定义属性都必须继承System.Attribute 

   2.自定义属性的类名称必须为 XXXXAttribute 即是已Attribute结尾

 [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]    public class MarkAttribute : Attribute    {        public MarkAttribute(string FiledName, string Description)        {            this.FiledName = FiledName;            this.Description = Description;        }        private string _FiledName;        public string FiledName        {            get { return _FiledName; }            set { _FiledName = value; }        }        private string _Description;        public string Description        {            get { return _Description; }            set { _Description = value; }        }    }    public class StudentEntity    {        public StudentEntity()        {        }        private string _Name;        [Mark("名称", "")]        public string Name        {            get { return _Name; }            set { _Name = value; }        }    }
4.通反射获取特性
 
      Type t = typeof(StudentEntity);            foreach (PropertyInfo p in t.GetProperties())            {                object[] Attribute1 = p.GetCustomAttributes(true);                object[] Attribute2 = p.GetCustomAttributes(typeof(MarkAttribute),false);            }



0 0