见代码
[TypeConverter(typeof(DescribedEnumConverter<FlatTypeEnum>))] public enum FlatTypeEnum { [Description("N")] N, [Description("F")] F } public static class EnumExtend<T> where T : Enum { public static T? GetEnumValueByDescription(string desc) { foreach (T item in Enum.GetValues(typeof(T))) { if (GetDescriptionByEnum(item) == desc) return item; } return default; } private static string GetDescriptionByEnum(Enum enumValue) { string value = enumValue.ToString(); System.Reflection.FieldInfo? field = enumValue.GetType().GetField(value); if (field == null) return value; object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 if (objs.Length == 0) //当描述属性没有时,直接返回名称 return value; DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return descriptionAttribute.Description; } }
文章评论