using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace Binance.TradeRobot.Common.Extensions { public static class EnumExtension { /// /// 从枚举中获取Description /// /// 需要获取枚举描述的枚举 /// 描述内容 public static string GetDescription(this System.Enum enumName) { var fieldInfo = enumName.GetType().GetField(enumName.ToString()); var attributes = GetDescriptAttr(fieldInfo); string description; if (attributes != null && attributes.Length > 0) { description = attributes[0].Description; } else { description = enumName.ToString(); } return description; } /// /// 根据 value 值获取Description /// /// /// /// public static string GetDescription(this Type enumType, int value) { var Key = GetNameAndValue(enumType).FirstOrDefault(p => p.Value.Equals(value)).Key; if (Key == null) return null; return Key.ToString(); } /// /// 获取字段Description /// /// FieldInfo /// DescriptionAttribute[] private static DescriptionAttribute[] GetDescriptAttr(FieldInfo fieldInfo) { if (fieldInfo != null) { return (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); } return null; } /// /// 获取枚举所有名称 /// /// 枚举类型typeof(T) /// 枚举名称列表 public static List GetEnumNamesList(this Type enumType) { return Enum.GetNames(enumType).ToList(); } /// /// 获取所有枚举对应的值 /// /// 枚举类型typeof(T) /// 枚举值列表 public static List GetEnumValuesList(this Type enumType) { var list = new List(); foreach (var value in System.Enum.GetValues(enumType)) { list.Add(Convert.ToInt32(value)); } return list; } /// /// 获取枚举名以及对应的Description /// /// 枚举类型typeof(T) /// 返回Dictionary ,Key为枚举名, Value为枚举对应的Description public static Dictionary GetNameAndDescriptions(this Type type) { if (type.IsEnum) { var dic = new Dictionary(); var enumValues = System.Enum.GetValues(type); foreach (System.Enum value in enumValues) { dic.Add(value, GetDescription(value)); } return dic; } return null; } /// /// 获取枚举名以及对应的Value /// /// 枚举类型typeof(T) /// 返回Dictionary ,Key为描述名, Value为枚举对应的值 public static Dictionary GetNameAndValue(this Type type) { if (type.IsEnum) { var dic = new Dictionary(); var enumValues = System.Enum.GetValues(type); foreach (System.Enum value in enumValues) { dic.Add(GetDescription(value), value.GetHashCode()); } return dic; } return null; } public static int GetValue(this System.Enum enumName) { return Convert.ToInt32(enumName.GetType().GetField(enumName.ToString()).GetValue(enumName)); } } }