繁体   English   中英

获取DisplayName属性的所有值

[英]Get the all the values of DisplayName attributes

我正在使用带有EntityFramework 6 DataAnnotations的asp.net MVC 5。 我想知道是否有一种方法来获取对象的所有DisplayName并将它们保存在变量中到Controller类中。

例如,考虑以下类:

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值? 例如,如何创建一个返回Dictionary< string,string >的函数,该Dictionary< string,string >具有属性名称和值为DisplayName的键,如下所示:

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

我已经看到了这个主题stackoverflow-获取DisplayName属性的值,但是我不知道扩展此代码的方法。

如果您不是很在意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);
            }
 }

我也提到了您在问题中提到的相同链接。

最终的字典是-

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM