C# 自定义特性Attribute要点

以自定义属性名称为例:

实现步骤

  1. 新增一个特性类:(其中AttributeUsage )可以修饰此特性类可修饰的类型)类命名后面习惯以(Attribute)结尾,如类名Display后面加Attribute作为类名,就是DisplayAttribute,此类要继承Attribute,创建一个构造函数,带一个(string)参数,用以初始化一个私有字段(自定义属性的名称),再加个公开返回此字段的方法:M
  2. 新增一个属性的扩展方法:静态类+静态方法,(this PropertyInfo propertyInfo),只要这一个参数,判断(propertyInfo.IsDefined)这个属性如果有第1步定义的特性类,则实例化(propertyInfo.GetCustomAttribute)特性类,调用第1步定义的方法:M
  3. 运用:在实体类定义里,在属性上面加特性类的名称:(DisplayAttribute),其中Attribute可以省略;
  4. 运用:在主函数里,反射遍历一个实体的属性,调用属性的静态方法返回属性的自定义名称,没有自定义名称就返回属性名称;
  5. 其他如验证属性值长度、必填等等的特性,区别在于:定义扩展方法时,第2个参数为类实体,也就是说要传入实体,如这样:public static bool LenghtRange(this PropertyInfo propertyInfo, Student student),多个student参数;
  6. 还可以给类、方法定义特性,通过反射不同的元数据(类或者方法MethodInfo)即可;

部分代码截取

  • 新增一个特性类:
    public class ZDisplayNameAttribute : Attribute
    {
        private string _DisplayName = null;
        //在类属性上方就可以使用特性了,语法:[ZDisplayName(自定义名称)],就相当于调用了这个构造函数
        public ZDisplayNameAttribute(string name)
        {
            this._DisplayName = name;
        }
        public string GetDisplayName()
        {
            return _DisplayName;
        }
    }
  • 新增一个属性的扩展方法:
        /// <summary>
        /// 反射类,遍历类所有属性(PropertyInfo),如果有指定特性,则调用此方法,就能返回自定义属性名称
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        public static string GetCusDisplayName(this PropertyInfo propertyInfo)
        {
            string _DisplayName = propertyInfo.Name;
            if (propertyInfo.IsDefined(typeof(ZDisplayNameAttribute), true))
            {
            //GetCustomAttribute,相当于创建特性类的对象
                var obj = (ZDisplayNameAttribute)propertyInfo.GetCustomAttribute(typeof(ZDisplayNameAttribute), true);
                _DisplayName = obj.GetDisplayName();
            }
            return _DisplayName;
        }
  • 定义一个类的时候,应用此特性
    public class Student
    {
        public int Id { get; set; }
        
        //相当于调用ZDisplayNameAttribute的构造函数
        [ZDisplayName("学生名称")]
        public string Name { get; set; }
        
		//调用ZLenghtRangeAttribute的构造函数
        [ZLenghtRange(10,20)]
        public string Password { get; set; }
    }
  • 特性应用
        public static void PrintInstance(Student student)
        {
            Type type = typeof(Student);
            var propertyInfos = type.GetProperties();

            foreach (PropertyInfo property in propertyInfos)
            {
            //调用属性的扩展方法 GetCusDisplayName()
                Console.WriteLine($"{property.GetCusDisplayName()}:	{property.GetValue(student)}	验证结果:{property.LenghtRange(student)}");

            }
        }
原文地址:https://www.cnblogs.com/zoulei0718/p/13589039.html