You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过反射获取类中值为True的属性的DisplayName列表?

获取Bool类型属性值为True的DisplayName列表

我需要从一个多数属性为bool类型的类中,提取所有值为True的属性的DisplayName,生成一个字符串列表。这个类的定义如下:

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; } 
}

我尝试通过遍历类的PropertyInfo来筛选值为True的属性,写了下面这段代码,但遇到了问题:那个GetPropertyDisplayName方法单独调用没问题,但没法在遍历过程中动态获取每个属性的DisplayName:

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) 
        { 
            // 这里单独调用GetPropertyDisplayName是可行的,但没法动态遍历构建列表
            // string displayName = GetPropertyDisplayName<AccessoriesModel>(i => i.AirConditioning); 
            list.Add(displayName); 
        } 
    } 
}

解决方案

其实不用依赖那个基于表达式树的GetPropertyDisplayName方法,我们可以直接在遍历PropertyInfo的时候,从属性上获取DisplayAttribute的Name值,这样就能动态处理每个符合条件的属性了。

完整实现代码

using System.ComponentModel.DataAnnotations;
using System.Reflection;

// 假设data是你的AccessoriesModel实例
AccessoriesModel data = new AccessoriesModel 
{
    Accessory1 = true,
    Accessory3 = true
};

List<string> selectedAccessoryNames = new List<string>();

foreach (PropertyInfo prop in data.GetType().GetProperties())
{
    // 只处理bool类型的属性
    if (prop.PropertyType == typeof(bool))
    {
        bool propertyValue = (bool)prop.GetValue(data);
        if (propertyValue)
        {
            // 获取属性上的Display特性
            DisplayAttribute displayAttribute = prop.GetCustomAttribute<DisplayAttribute>();
            
            // 如果存在Display特性,就用它的Name;否则 fallback 到属性本身的名称(可选)
            string displayName = displayAttribute?.Name ?? prop.Name;
            
            selectedAccessoryNames.Add(displayName);
        }
    }
}

// 此时selectedAccessoryNames会包含["Acc 1", "Acc 3"]

如果你想复用原有的方法

如果你还是想保留原来的GetPropertyDisplayName逻辑,可以把它改造成接受PropertyInfo参数的版本,这样遍历的时候就能直接传入当前属性了:

public static string GetPropertyDisplayName(PropertyInfo propertyInfo)
{
    var displayAttr = propertyInfo.GetCustomAttribute<DisplayAttribute>();
    return displayAttr?.Name ?? propertyInfo.Name;
}

然后在遍历代码里替换成:

string displayName = GetPropertyDisplayName(prop);
list.Add(displayName);

这样就能完美实现你想要的效果啦!

内容的提问来源于stack exchange,提问作者Ionea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:12:33