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

C#枚举Description属性问题:如何仅在ComboBox展示描述文本?

解决ComboBox仅显示枚举Description属性的方法

首先先规范你的枚举定义(修正拼写错误,示例如下):

public enum SnackType
{
    [Description("Chocolate Bar")]
    ChocolateBar,
    [Description("Caffe Protein Bar")]
    CafeProteinBar,
    [Description("Vanilla Cookie")]
    VanillaCookie
}

步骤1:编写获取枚举Description的工具方法

实现一个静态方法,专门提取枚举项的Description属性值,若未定义则返回枚举本身的名称:

using System.ComponentModel;
using System.Reflection;

public static class EnumHelper
{
    public static string GetDescription(Enum enumValue)
    {
        FieldInfo fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
        
        return attributes.Length > 0 ? attributes[0].Description : enumValue.ToString();
    }
}

步骤2:绑定枚举到ComboBox(两种实用方式)

方式1:手动遍历填充

适合WinForms场景,直接控制每一项的显示文本与对应值:

// 清空ComboBox原有项
yourComboBox.Items.Clear();

foreach (SnackType snack in Enum.GetValues(typeof(SnackType)))
{
    string desc = EnumHelper.GetDescription(snack);
    // 绑定描述文本和枚举值,仅显示描述
    yourComboBox.Items.Add(new { DisplayText = desc, EnumValue = snack });
}

// 设置显示和值的成员
yourComboBox.DisplayMember = "DisplayText";
yourComboBox.ValueMember = "EnumValue";

方式2:通过LINQ生成集合绑定

更简洁的写法,适合需要数据绑定的场景:

var snackItems = Enum.GetValues(typeof(SnackType))
                     .Cast<SnackType>()
                     .Select(s => new 
                     { 
                         DisplayText = EnumHelper.GetDescription(s), 
                         EnumValue = s 
                     })
                     .ToList();

yourComboBox.DataSource = snackItems;
yourComboBox.DisplayMember = "DisplayText";
yourComboBox.ValueMember = "EnumValue";

注意事项

  • 必须引用System.ComponentModel和System.Reflection命名空间,否则无法调用DescriptionAttribute与反射相关API。
  • 获取用户选择的枚举值时,直接通过yourComboBox.SelectedValue强转为对应枚举类型即可使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 11:42:25