• 读取 DisplayName和Display(Name='')


     public class UserClass
        {
           
            [DisplayName("名称")] //DisplayName
            public string Name { get; set; }
            [Display(Name = "年龄")]//Display
            public string Age { get; set; }
            [Display(Name = "性别")]
            public string Sex { get; set; }
            [Display(Name = "地址")]
            public string Address { get; set; }
            [Display(Name = "手机号")]
            public string Phone { get; set; }
            [Display(Name = "邮箱")]
            public string Email { get; set; }
        }

    代码

     /// <summary>
            /// 动态获取 DisplayName和Display(Name='')
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            /// <returns></returns>
            public static List<Dictionary<string, string>> GetClassDesc<T>(T t)
            {
                List<Dictionary<string, string>> dicList = new List<Dictionary<string, string>>();
                Dictionary<string, string> dic;
                Type type = t.GetType();
                PropertyInfo[] ProInfo = type.GetProperties();
                foreach (var item in ProInfo)
                {
                    if (dicList.Count > 0)
                    {
                        //获取Display(Name='')
                        dic = new Dictionary<string,string>();
                        var attribute = type.GetProperty(item.Name);
                        var displayName = attribute.GetCustomAttribute<DisplayAttribute>();
                        dic.Add(item.Name, displayName.Name);
                        dicList.Add(dic);
                    }
                    else
                    {
                        //获取 DisplayName
                        dic = new Dictionary<string, string>();
                        var attribute = type.GetProperty(item.Name);
                        var displayName = attribute.GetCustomAttribute<DisplayNameAttribute>();
                        dic.Add(item.Name, displayName.DisplayName);
                        dicList.Add(dic);
                    }
                }
                return dicList;
            }

    //调用代码

       List<Dictionary<string, string>> dicList = GetClassDesc<UserClass>(Us);
                
                foreach (Dictionary<string,string> item in dicList)
                {
                    string Name = item["Name"];//名称
                }

  • 相关阅读:
    GitHub 源码,Framework 框架
    转int啥啥啥的
    查看apk签名 和 keystore 的信息
    一次apk打开时报内存溢出错误,故写下内存溢出的各种原因和解决方法
    客户端传值里面包含URL特殊字符的应对方法
    Linux全硬盘搜索文件名是xxxxx的命令
    pythonmysql运行报错解决过程中遇到的其中一个报错解决文章来源
    linux查看硬盘占用情况
    Linux使用nginx反向代理。可实现域名指向特定端口
    Linux下使用yum安装软件命令
  • 原文地址:https://www.cnblogs.com/szlblog/p/7942931.html
Copyright © 2020-2023  润新知