using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Concurrent; using System.Reflection; using System.ComponentModel.DataAnnotations; using System.ComponentModel; namespace Bowin.Common.Utility { /// /// Enum 的扩展 /// public static class EnumExtension { private static ConcurrentDictionary _cache = new ConcurrentDictionary(); public static string GetDisplayName(this Enum source) { var enumType = source.GetType(); string name = Enum.GetName(enumType, source); var key = string.Concat(enumType.Name, "-", name); if (_cache.ContainsKey(key)) { return _cache[key]; } var enumDisplay = source.GetAttribute(); if (enumDisplay != null) { _cache[key] = enumDisplay.Name; return enumDisplay.Name; } var enumDescription = source.GetAttribute(); if (enumDescription != null) { _cache[key] = enumDescription.Description; return enumDescription.Description; } _cache[key] = source.ToString(); return source.ToString(); } public static T GetAttribute(this Enum source) where T : Attribute { Type enumType = source.GetType(); string name = Enum.GetName(enumType, source); if (name != null) { FieldInfo fieldInfo = enumType.GetField(name); if (fieldInfo != null) { return fieldInfo.GetAttribute(); } } return null; } } }