Populate list from enum
我想填充一个同时提供枚举值和描述的列表。我怎么用C来做这个?
我知道如何创建一个值列表,但我也希望包括这些描述。我的Enums是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 | using System.ComponentModel; public enum BusinessCategory { [Description("Computers & Internet")] ComputersInternet = 1, [Description("Finance & Banking")] FinanceBanking = 2, [Description("Healthcare")] Healthcare = 3, [Description("Manufacturing")] Manufacturing = 4 } |
我希望我的列表看起来像:
1 2 3 4 5 6 | [ { 1,"Computers & Internet" }, { 2,"Finance & Banking" }, { 3,"Healthcare" }, { 4,"Manufacturing" } ] |
您可以通过调用
之后,您可以检索每个值的描述,如下所述:
- 如何从值中获取C枚举描述?
首先,您需要通过调用
在需要获取描述属性值之后,应该使用反射。下面是代码(您可以运行它https://dotnetfiddle.net/chgean):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | using System; using System.ComponentModel; using System.Reflection; using System.Linq; public enum BusinessCategory { [Description("Computers & Internet")] ComputersInternet = 1, [Description("Finance & Banking")] FinanceBanking = 2, [Description("Healthcare")] Healthcare = 3, [Description("Manufacturing")] Manufacturing = 4 } public class Program { public static void Main() { // Get all possible values var values = Enum.GetValues(typeof(BusinessCategory)).Cast<BusinessCategory>(); foreach(var v in values) { // Write to the console info about each value Console.WriteLine("{0}[{1}] => {2}", v, (int)v, v.GetEnumDescription()); } } } public static class EnumExtensions { public static string GetEnumDescription(this Enum value, string defaultValue = null) { return value.GetEnumAttribute<DescriptionAttribute>(a => a.Description, defaultValue); } private static string GetEnumAttribute<TAttr>(this Enum value, Func<TAttr, string> expr, string defaultValue = null)where TAttr : Attribute { FieldInfo fi = value.GetType().GetField(value.ToString()); var attributes = fi.GetCustomAttributes<TAttr>(false).ToArray(); return (attributes != null && attributes.Length > 0) ? expr(attributes.First()) : (defaultValue ?? value.ToString()); } } |
您可以使用反射和Linq来执行以下操作:
1 2 3 | var enums = typeof(BusinessCategory).GetFields().Skip(1) .Select(x => Tuple.Create((BusinessCategory)x.GetValue(null), x.GetCustomAttributes<DescriptionAttribute>().First().Description)); |
这将返回将枚举映射到其描述属性的元组集合。
我不得不跳过第一个元素,因为我找不到不会从枚举返回隐藏的int字段