zoukankan      html  css  js  c++  java
  • 读取 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"];//名称
                }

  • 相关阅读:
    图文详解QT布局管理器
    osg中放大缩小模型
    osgearth中XML文档读取报错
    中国河南省洛阳市嵩县黄庄乡红堂村大树芽组
    GIS数据下载整合
    四面体剖分相关开源软件列表
    在你的QT工程中使用ui文件
    对osgAnimation例子的注释的注释
    [debug]调试Release版本应用程序
    链表面试题总结
  • 原文地址:https://www.cnblogs.com/szlblog/p/7942931.html
Copyright © 2011-2022 走看看