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

如何在C#中获取包含枚举名称与描述的列表?

解决方法

要得到你需要的枚举名称+描述的格式,核心是读取枚举字段上的DescriptionAttribute属性值,再和枚举名称配对。可以按以下步骤实现:

1. 编写获取枚举描述的扩展方法

先创建一个静态类,添加扩展方法来读取枚举的Description属性:

using System.ComponentModel;
using System.Reflection;

public static class EnumExtensions
{
    public static string GetDescription(this Enum enumValue)
    {
        // 获取枚举字段的反射信息
        var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
        // 读取DescriptionAttribute
        var descriptionAttr = fieldInfo.GetCustomAttribute<DescriptionAttribute>();
        // 如果有描述则返回,没有就返回枚举本身的名称
        return descriptionAttr?.Description ?? enumValue.ToString();
    }
}

2. 生成目标格式的列表

使用LINQ遍历枚举值,结合上面的扩展方法,生成包含枚举名称和描述的集合:

using System.Linq;

// 获取所有PaymentType枚举值,并转换为包含名称和描述的集合
var paymentTypeList = Enum.GetValues(typeof(PaymentType))
                          .Cast<PaymentType>()
                          .Select(type => new 
                          {
                              EnumName = type.ToString(),
                              Description = type.GetDescription()
                          })
                          .ToList();

3. 输出目标格式

如果需要打印成你展示的文本格式,直接遍历集合输出即可:

foreach (var item in paymentTypeList)
{
    Console.WriteLine($"{item.EnumName} {item.Description}");
}

运行后会得到如下输出:

DD Direct Debit
EFT EFT
LCk Live Check
Other Other
None None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 09:13:17