using System.Collections.Concurrent; using System.ComponentModel; using System.Reflection; namespace Easy.Core; public static class EnumExtension { /// /// 缓存 /// private static readonly ConcurrentDictionary EnumDic = new(); /// /// 获取枚举上定义的Description /// /// /// public static string Description(this Enum value) { Type type = value.GetType(); string vs = value.ToString(), key = $"{type.FullName}_{vs}"; if (EnumDic.TryGetValue(key, out var description)) { return description; } FieldInfo fieldInfo = type.GetField(vs); if (fieldInfo != null && fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() is DescriptionAttribute descriptionAttribute) { string desc = descriptionAttribute.Description; EnumDic.TryAdd(key, desc); return desc; } return string.Empty; } /// /// 将 int 值转换为指定枚举类型 /// /// 枚举类型 /// int 值 /// 枚举值,如果转换失败则返回 null public static T? ToEnum(this int value) where T : struct, Enum { if (Enum.IsDefined(typeof(T), value)) { return (T)(object)value; } return null; } /// /// 将 int? 值转换为指定枚举类型 /// /// 枚举类型 /// int? 值 /// 枚举值,如果转换失败则返回 null public static T? ToEnum(this int? value) where T : struct, Enum { if (!value.HasValue) return null; return value.Value.ToEnum(); } /// /// 将 long 值转换为指定枚举类型 /// /// 枚举类型 /// long 值 /// 枚举值,如果转换失败则返回 null public static T? ToEnum(this long value) where T : struct, Enum { if (Enum.IsDefined(typeof(T), value)) { return (T)(object)value; } return null; } /// /// 将 long? 值转换为指定枚举类型 /// /// 枚举类型 /// long? 值 /// 枚举值,如果转换失败则返回 null public static T? ToEnum(this long? value) where T : struct, Enum { if (!value.HasValue) return null; return value.Value.ToEnum(); } /// /// 获取枚举所有值及其 Description 的字典 /// /// 枚举类型 /// 字典,Key为枚举值,Value为Description public static Dictionary GetDescriptionDictionary() where T : struct, Enum { var result = new Dictionary(); var values = Enum.GetValues(typeof(T)); foreach (var value in values) { if (value is T enumValue) { result[enumValue] = enumValue.Description(); } } return result; } /// /// 获取枚举所有值的列表(包含值和Description) /// /// 枚举类型 /// 枚举选项列表 public static List> GetEnumOptions() where T : struct, Enum { var result = new List>(); var values = Enum.GetValues(typeof(T)); foreach (var value in values) { if (value is T enumValue) { result.Add(new EnumOption { Value = enumValue, Description = enumValue.Description() }); } } return result; } } /// /// 枚举选项 /// /// 枚举类型 public class EnumOption where T : struct, Enum { /// /// 枚举值 /// public T Value { get; set; } /// /// 描述 /// public string Description { get; set; } = string.Empty; }