using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace QYZH.InteractiveMagazine.Common.Helpers { /// /// 枚举工具类 /// public static class EnumHelper { /// /// 根据枚举名称获取枚举值 /// /// 枚举类型 /// 枚举名称 /// 枚举值 public static TEnum GetValue(string name) where TEnum : Enum { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("枚举名称不能为空", nameof(name)); } if (Enum.TryParse(typeof(TEnum), name, true, out object? result)) { return (TEnum)result; } throw new ArgumentException($"枚举 '{typeof(TEnum).Name}' 中不存在名称为 '{name}' 的值"); } /// /// 根据枚举值获取枚举名称 /// /// 枚举类型 /// 枚举值 /// 枚举名称 public static string GetName(object value) where TEnum : Enum { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (Enum.IsDefined(typeof(TEnum), value)) { return Enum.GetName(typeof(TEnum), value)!; } throw new ArgumentException($"枚举 '{typeof(TEnum).Name}' 中不存在值 '{value}'"); } /// /// 获取枚举的所有值 /// /// 枚举类型 /// 枚举值列表 public static List GetAllValues() where TEnum : Enum { return Enum.GetValues(typeof(TEnum)).Cast().ToList(); } /// /// 根据Description获取枚举值 /// /// 枚举类型 /// 描述文本 /// 枚举值 public static TEnum GetValueByDescription(string description) where TEnum : Enum { if (string.IsNullOrWhiteSpace(description)) { throw new ArgumentException("描述不能为空", nameof(description)); } foreach (TEnum value in Enum.GetValues(typeof(TEnum))) { string desc = GetDescription(value); if (desc.Equals(description, StringComparison.OrdinalIgnoreCase)) { return value; } } throw new ArgumentException($"枚举 '{typeof(TEnum).Name}' 中不存在描述为 '{description}' 的值"); } /// /// 获取枚举的DescriptionAttribute描述 /// /// 枚举类型 /// 枚举值 /// 描述文本 public static string GetDescription(TEnum value) where TEnum : Enum { System.Reflection.FieldInfo? field = value.GetType().GetField(value.ToString()); if (field == null) { return value.ToString(); } var attribute = (DescriptionAttribute?)Attribute.GetCustomAttribute( field, typeof(DescriptionAttribute)); return attribute?.Description ?? value.ToString(); } } }