using System; using System.Collections.Generic; using System.ComponentModel; 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(); var attr2 = field.GetCustomAttribute(); if (attr == null && attr2 == null) { return enumType.ToString(); } else if (attr == null && attr2 != null) { if (string.IsNullOrWhiteSpace(attr2.Description)) return enumType.ToString(); else return attr2.Description; } else if (attr != null && attr2 != null) { if (!string.IsNullOrWhiteSpace(attr.Name)) return attr.Name; if (!string.IsNullOrWhiteSpace(attr2.Description)) return attr2.Description; return enumType.ToString(); } else { if (string.IsNullOrWhiteSpace(attr.Name)) return enumType.ToString(); else return attr.Name; } } catch { return enumType.ToString(); } } 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(); DescriptionAttribute da = type.GetField(text).GetCustomAttribute(); T result; if (customAttribute == null && da == null) { if (text == displayName && Enum.TryParse(text, out result)) { return result; } continue; } string a; if (customAttribute != null) { 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); } } else { if (da == null && string.IsNullOrEmpty(da.Description)) { a = text; } else { a = (string.IsNullOrEmpty(da.Description) ? text : da.Description); } } if (a == displayName && System.Enum.TryParse(text, out result)) { return result; } } throw new Exception($"{displayName}转换为枚举{typeof(T)}失败"); } }