如何在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
相关产品推荐
相关产品推荐

