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"];//名称
                }

  • 相关阅读:
    C# WinForm 中 MessageBox的使用详解
    C#中MemoryStream类的介绍
    C#中String类的几个方法(IndexOf、LastIndexOf、Substring)
    C#ImageList和ListView的使用
    ListView的BeginUpdate()和EndUpdate()的用处
    C#中AppDomain.CurrentDomain.BaseDirectory及各种路径获取方法
    C#字符串比较方法
    C# ListView用法详解
    c#中枚举类型的定义与使用
    c#中的模态对话框和非模态对话框
  • 原文地址:https://www.cnblogs.com/szlblog/p/7942931.html
Copyright © 2011-2022 走看看