特性

特性:一个直接或间接继承自Attribute的类,一般以Attribute结尾,声明时候可以省略掉

//AttributeTargets表示修饰对象  AllowMultiple表示是否可以多次修饰
    [AttributeUsage(AttributeTargets.All,AllowMultiple =true)]
    [Obsolete("牛的",false)]//为false则是报警告,true为报错
    public class CustomAttribute:Attribute
    {
        //构造函数
        public CustomAttribute()
        {

        }
        //构造函数重载
        public CustomAttribute(int n)
        {

        }
        //属性
        public string ID { get; set; }
        //字段
        public string _id;
    }

 找被特性修饰的元素

                //
                Type type = typeof(Stu);
                if (type.IsDefined(typeof(CustomAttribute), true))
                {
                    CustomAttribute attribute=(CustomAttribute)type.GetCustomAttribute(typeof(CustomAttribute), true);
                }
                //属性
                PropertyInfo property = type.GetProperty("属性名");
                if (property.IsDefined(typeof(CustomAttribute), true))
                {
                    CustomAttribute attribute = (CustomAttribute)property.GetCustomAttribute(typeof(CustomAttribute), true);
                }
                //方法
                MethodInfo method = type.GetMethod("方法名");
                if (method.IsDefined(typeof(CustomAttribute), true))
                {
                    CustomAttribute attribute = (CustomAttribute)method.GetCustomAttribute(typeof(CustomAttribute), true);
                }
                //参数
                ParameterInfo parameter = method.GetParameters()[0];
                if (parameter.IsDefined(typeof(CustomAttribute), true))
                {
                    CustomAttribute attribute = (CustomAttribute)parameter.GetCustomAttribute(typeof(CustomAttribute), true);
                }
原文地址:https://www.cnblogs.com/TheLin/p/14337084.html