using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Concurrent; using System.ComponentModel; namespace Bowin.Common.Exceptions { public class EnumHelper { static ConcurrentDictionary> _listItemCache = new ConcurrentDictionary>(); /// /// 将枚举转换成Dictionary<int, string> /// Dictionary中,key为枚举项对应的int值;value为:若定义了Description属性,则取它,否则取name /// /// /// public static Dictionary EnumToDictionary(Type enumType) { Dictionary items; if (!_listItemCache.TryGetValue(enumType, out items)) { items = new Dictionary(); foreach (int i in Enum.GetValues(enumType)) { var name = Enum.GetName(enumType, i); //取显示名称 string showName = string.Empty; object[] atts = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false); if (atts.Length > 0) showName = ((DescriptionAttribute)atts[0]).Description; items.Add(i, string.IsNullOrEmpty(showName) ? name : showName); } _listItemCache[enumType] = items; } return items; } /// /// 获取枚举值对应的显示名称 /// /// 枚举类型 /// 枚举项对应的int值 /// public static string GetEnumShowName(Type enumType, int value) { return EnumToDictionary(enumType)[value]; } } }