我正在尝试从具有大多数属性布尔值的类中获取 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; }
}
通过遍历类的 PropertyInfos 并查看哪些值为 true,如下所示:
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 是其他成员在回答另一个用于检索属性的 DisplayName 的问题时建议的解决方案:https ://stackoverflow.com/a/10048758
我正在寻找的最终结果是一个字符串列表(显示名称),它将仅由为真的属性形成。
预先感谢您对此的帮助。