获取 DisplayName 属性的所有值

Get the all the values of DisplayName attributes

我正在使用 asp.net MVC 5 和 EntityFramework 6 DataAnnotations。 我想知道是否有办法获取对象的所有 DisplayName 并将它们保存在变量中到控制器 class.

例如,考虑 class:

public class Class1
{
    [DisplayName("The ID number")]
    public int Id { get; set; }

    [DisplayName("My Value")]
    public int Value { get; set; }

    [DisplayName("Label name to display")]
    public string Label { get; set; }
}

如何获取所有属性的DisplayName值?例如,如何创建一个 returns 一个 Dictionary< string,string > 的函数,它有一个带有属性名称和值 DisplayName 的键,如下所示:

{ "Id": "The ID name", "Value": "My Value", "Label": "Label name to display"}.

我看过这个主题 Whosebug - get the value of DisplayName attribute 但我不知道如何扩展此代码。

如果您真的不关心 DisplayName 属性,而是关心将要使用的有效显示名称(例如通过数据绑定),最简单的方法是使用 TypeDescriptor.GetProperties 方法:

var info = TypeDescriptor.GetProperties(typeof(Class1))
    .Cast<PropertyDescriptor>()
    .ToDictionary(p => p.Name, p => p.DisplayName);

您可以使用下面的代码 -

 Class1 c = new Class1();
 PropertyInfo[] listPI = c.GetType().GetProperties();
 Dictionary<string, string> dictDisplayNames = new Dictionary<string, string>();
 string displayName = string.Empty;

 foreach (PropertyInfo pi in listPI)
 {
    DisplayNameAttribute dp = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().SingleOrDefault();
            if (dp != null)
            {
                displayName = dp.DisplayName;
                dictDisplayNames.Add(pi.Name, displayName);
            }
 }

我也提到了你在问题中提到的相同 link。

最终词典为 -