using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace IRaCIS.Core.Infrastructure.Extention { public static class EnumToSelectExtension { /// /// 将枚举转换成字典(枚举,自定义描述) /// /// /// 需要排除的枚举 /// public static Dictionary ToSelect( params TEnum[] exceptList) where TEnum : struct, Enum { var type = typeof(TEnum); var dict = new Dictionary(); foreach (var value in Enum.GetValues()) //foreach (var value in type.GetEnumValues()) { var attr = type.GetField(value.ToString()) .GetCustomAttribute(); if (attr is null || exceptList.Contains(value)) continue; var key = type.GetFields().FirstOrDefault(t=>t.Name== value.ToString()).GetRawConstantValue(); dict[key] = attr.Description; } return dict; } /// /// 扩展方法,获得枚举的Description /// /// 枚举值 /// 当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用 /// 枚举的Description public static string GetDescription(this Enum value, Boolean nameInstead = true) { Type type = value.GetType(); string name = Enum.GetName(type, value); if (name == null) { return null; } FieldInfo field = type.GetField(name); DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && nameInstead == true) { return name; } return attribute?.Description; } } }