C#可以通过反射,来获取枚举的描述信息或通过描述信息获取到指定类型的枚举
1 /// <summary> 2 /// 获取枚举描述 3 /// </summary> 4 /// <param name="enumName"></param> 5 /// <returns></returns> 6 public static string GetDescription(this Enum enumName) 7 { 8 string description; 9 FieldInfo fieldInfo = enumName.GetType().GetField(enumName.ToString()); 10 DescriptionAttribute[] attributes = fieldInfo.GetDescriptAttr(); 11 if (attributes != null && attributes.Length > 0) 12 description = attributes[0].Description; 13 else 14 throw new ArgumentException($"{enumName} 未能找到对应的枚举描述.", nameof(enumName)); 15 return description; 16 } 17 18 /// <summary> 19 /// 获取枚举描述属性 20 /// </summary> 21 /// <param name="fieldInfo"></param> 22 /// <returns></returns> 23 private static DescriptionAttribute[] GetDescriptAttr(this FieldInfo fieldInfo) 24 { 25 return (DescriptionAttribute[])fieldInfo?.GetCustomAttributes(typeof(DescriptionAttribute), false); 26 } 27 28 /// <summary> 29 /// 通过描述获取枚举值 30 /// </summary> 31 /// <typeparam name="TEnum"></typeparam> 32 /// <param name="description"></param> 33 /// <returns></returns> 34 public static TEnum GetEnum<TEnum>(string description) 35 { 36 Type type = typeof(TEnum); 37 foreach (FieldInfo field in type.GetFields()) 38 { 39 DescriptionAttribute[] curDesc = field.GetDescriptAttr(); 40 if (curDesc != null && curDesc.Length > 0) 41 { 42 if (curDesc[0].Description == description) 43 return (TEnum)field.GetValue(null); 44 } 45 else 46 { 47 if (field.Name == description) 48 return (TEnum)field.GetValue(null); 49 } 50 } 51 throw new ArgumentException($"{description} 未能找到对应的枚举.", nameof(description)); 52 }
时间: 2024-11-29 03:31:53