• 泛型+反射+特性的使用


    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.调用

  • 相关阅读:
    沙雕玩意儿
    1558:聚会 ybt
    沙雕关于线段树的一点总结(滑稽)
    卑微
    沙雕题目 来自luogu
    甜茶好帅啊
    python 中字符串的格式化
    python的几个小程序
    python 第一课
    基于笔画宽度变换的自然场景文本检测方法
  • 原文地址:https://www.cnblogs.com/sunff/p/12915894.html
Copyright © 2020-2023  润新知