1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- 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
- {
- /// <summary>
- /// Enum 的扩展
- /// </summary>
- public static class EnumExtension
- {
- private static ConcurrentDictionary<string, string> _cache = new ConcurrentDictionary<string, string>();
- 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<DisplayAttribute>();
- if (enumDisplay != null)
- {
- _cache[key] = enumDisplay.Name;
- return enumDisplay.Name;
- }
- var enumDescription = source.GetAttribute<DescriptionAttribute>();
- if (enumDescription != null)
- {
- _cache[key] = enumDescription.Description;
- return enumDescription.Description;
- }
- _cache[key] = source.ToString();
- return source.ToString();
- }
- public static T GetAttribute<T>(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<T>();
- }
- }
- return null;
- }
- }
- }
|