泛型+反射+特性的使用

1.创建一个特性

 1     //限制特性使用,AttributeTargets限制使用对象,AllowMultiple限制在同一个对象是否可以重复使用,Inherited是否继承
 2     [AttributeUsage(AttributeTargets.Property,AllowMultiple =false,Inherited =true)]
 3     public class ShowAttribute:Attribute//必须继承这个类
 4     {
 5         public string _sValue;
 6         /// <summary>
 7         /// 这个方法反射调用
 8         /// </summary>
 9         /// <param name="sValue"></param>
10         public ShowAttribute(string sValue) {
11             this._sValue = sValue;
12         }
13     }

2.在某个类使用特性

    public class SysUserModel
    {
        //Show ShowAttribute都可以
        [Show("用户Id")]
        public int Id { get; set; }
        [ShowAttribute("用户姓名")]
        public string Name { get; set; }
        [Show("用户账号")]
        public string Account { get; set; }
        [Show("用户密码")]
        public string Password { get; set; }
    }

3.通过反射检测、使用特性

        public static void ShowAttributeInfo<T>(this T t)
        {
            Type type = t.GetType();
            foreach (var prop in type.GetProperties())
            {
                //判断属性是否包含这个特性
                if (prop.IsDefined(typeof(ShowAttribute), true)) {
                    //通过GetCustomAttribute方法获取特性实例,后面就是自己想怎么干就怎么干了
                    ShowAttribute s = (ShowAttribute)prop.GetCustomAttribute(typeof(ShowAttribute), true);
                    Console.WriteLine($"{s._sValue}:{prop.GetValue(t)}");
                }
            }
        }

4.调用

 

posted on 2020-05-19 11:24  不朽阁主  阅读(205)  评论(0编辑  收藏  举报

导航