123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- 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<Type, Dictionary<int, string>> _listItemCache =
- new ConcurrentDictionary<Type, Dictionary<int, string>>();
- /// <summary>
- /// 将枚举转换成Dictionary<int, string>
- /// Dictionary中,key为枚举项对应的int值;value为:若定义了Description属性,则取它,否则取name
- /// </summary>
- /// <param name="enumType"></param>
- /// <returns></returns>
- public static Dictionary<int, string> EnumToDictionary(Type enumType)
- {
- Dictionary<int, string> items;
- if (!_listItemCache.TryGetValue(enumType, out items))
- {
- items = new Dictionary<int, string>();
- 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;
- }
- /// <summary>
- /// 获取枚举值对应的显示名称
- /// </summary>
- /// <param name="enumType">枚举类型</param>
- /// <param name="value">枚举项对应的int值</param>
- /// <returns></returns>
- public static string GetEnumShowName(Type enumType, int value)
- {
- return EnumToDictionary(enumType)[value];
- }
- }
- }
|