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