使用反射从 Class 属性中获取 DisplayNames 列表

Using reflection to obtain list of DisplayNames from Class properties

我正在尝试从具有大部分属性布尔值的 class 中获取 DisplayNames 列表:

public class AccessoriesModel
{
    public int Id { get; set; }

    [Display(Name = "Acc 1")]
    public bool Accessory1 { get; set; }

    [Display(Name = "Acc 2")]
    public bool Accessory2 { get; set; }

    [Display(Name = "Acc 3")]
    public bool Accessory3 { get; set; }

    [Display(Name = "Acc 4")]
    public bool Accessory4 { get; set; }
}

通过遍历 class 的 PropertyInfos 并查看哪些值为真,如下所示:

    List<string> list = new List<string>();
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
        {
            if (propertyInfo.PropertyType == typeof(bool))
            {
                bool value = (bool)propertyInfo.GetValue(data, null);

                if (value)
                {
                   //add the DisplayName of the item who's value is true to the list named "list"

                   //the following line works fine, but I cannot iterate over the list of items to get dinamicaly build the list
                   string displayName = GetPropertyDisplayName<AccessoriesModel>(i => i.AirConditioning);

                   list.add(displayName)

                }
            }
        }

其中 GetPropertyDisplayName 是一位同事在回答另一个检索 属性 的显示名称的问题时建议的解决方案:

我正在寻找的最终结果是一个字符串列表(显示名称),它将仅由真实的属性组成。

在此先感谢您的帮助。

我认为您使用了错误的属性。我只是从 中摘录了一个片段,并将 "DisplayNameAttribute" 替换为 "DisplayAttribute",我得到了工作结果。

您引用的示例代码具有如下属性:

public class Class1
{
    [DisplayName("Something To Name")]
    public virtual string Name { get; set; }

你的是这样的:

public class AccessoriesModel
{
    public int Id { get; set; }

    [Display(Name = "Acc 1")]
    public bool Accessory1 { get; set; }

因此,属性使用方面的差异可能是它不适合您的原因。休息一下,您可以在下面找到工作代码:

foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
    if (propertyInfo.PropertyType == typeof(bool))
    {
        bool value = (bool)propertyInfo.GetValue(data, null);
        if (value)
        {
            var attribute = propertyInfo.GetCustomAttributes(typeof(DisplayAttribute), true)
                                .Cast<DisplayAttribute>().Single();
            string displayName = attribute.Name;
            list.Add(displayName);
        }
    }
}

我重用了这个答案中的扩展方法