/// <summary> /// 获得指定枚举值的第一个描述 /// (即获取枚举的自定义特性EnumDescriptionAttribute的Description属性) /// </summary> /// <param name="value">枚举值</param> /// <param name="decriptionTag">对枚举的描述的分类标签</param> /// <returns></returns> public static string GetDescription(Enum value, int decriptionTag = 0) { if (value == null) { throw new ArgumentException("枚举参数value为空!"); } string name = value.ToString(); string description = name; var fieldInfo = value.GetType().GetField(name); var attributes = (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false); if (attributes.Length > 0) { EnumDescriptionAttribute attribute = null; foreach (var att in attributes) { if (att.DescriptionTag == decriptionTag) { attribute = att; break; } } description = attribute?.Description; } return(description); }
/// <summary> /// 获得枚举的所有枚举值的名称和第一个描述的键值对,T必须是枚举类型 /// </summary> /// <param name="decriptionTag">对枚举的描述的分类标签</param> /// <returns></returns> public static Dictionary <string, string> GetNameAndDescriptionDict <T>(int decriptionTag) where T : struct { var enumType = typeof(T); string[] names = Enum.GetNames(enumType); Dictionary <string, string> result = new Dictionary <string, string>(); foreach (var name in names) { var fieldInfo = enumType.GetField(name); var attributes = (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false); if (attributes.Length > 0) { EnumDescriptionAttribute attribute = null; foreach (var att in attributes) { if (att.DescriptionTag == decriptionTag) { attribute = att; break; } } result.Add(name, attribute == null ? name : attribute.Description); } else { result.Add(name, name); } } return(result); }