using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Resources; using System.Text; using System.Threading.Tasks; /// /// 枚举扩展 /// public static class EnumExtension { /// /// 获取枚举描述 /// /// 枚举类型 /// public static string GetEnumDisplayName(this Enum enumType) { try { Type type = enumType.GetType(); var field = type.GetField(Enum.GetName(type, enumType)); var attr = field.GetCustomAttribute(); if (attr == null || string.IsNullOrWhiteSpace(attr.Name)) return enumType.ToString(); else return attr.Name; } catch { return string.Empty; } } public static T GetEnumByDisplayName(this string displayName) where T : struct { Type type = typeof(T); string[] names = Enum.GetNames(type); string[] array = names; foreach (string text in array) { DisplayAttribute customAttribute = type.GetField(text).GetCustomAttribute(); T result; if (customAttribute == null) { if (text == displayName && Enum.TryParse(text, out result)) { return result; } continue; } string a; if (customAttribute.ResourceType == null && string.IsNullOrEmpty(customAttribute.Name)) { a = text; } else if (!(customAttribute.ResourceType != null)) { a = (string.IsNullOrEmpty(customAttribute.Name) ? text : customAttribute.Name); } else { ResourceManager resourceManager = new ResourceManager(customAttribute.ResourceType); a = resourceManager.GetString(customAttribute.Name); } if (a == displayName && System.Enum.TryParse(text, out result)) { return result; } } return (T)System.Enum.Parse(type, "0"); } }