方法一: 使用[Display(Name="描述")]特性
public namespace My.Test.Application { /// <summary> /// 定义枚举 /// </summary> public enum ExpendRecordStatusEnum { /// <summary> /// 正常销售 /// </summary> [Display(Name = "正常销售")] NormalSale = 4, /// <summary> /// 退换 /// </summary> [Display(Name = "退换单据")] Replacement = 5 } /// <summary> /// 枚举帮助 /// </summary> public static class EnumHelper { /// <summary> /// 获得枚举量的Display[name=""]特性 /// </summary> /// <param name="eum"></param> /// <returns></returns> public static string GetDisplayName(this System.Enum eum) { var type = eum.GetType(); //先获取这个枚举的类型 var field = type.GetField(eum.ToString()); //通过这个类型获取到值 var obj = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute)); //得到特性 return obj.Name ?? ""; } } /// <summary> /// 枚举测试类 /// </summary> public class TestEnum { /// <summary> /// 获取到字典描述值 /// </summary> /// <returns></returns> public string SearchEnumDisplayName() { return ExpendRecordStatusEnum.NormalSale.GetDisplayName(); } } }
方法二: 使用[DisplayName("描述")]特性
注意:在netcore 3.1中无法使用DisplayName特性
public namespace My.Test.Application { /// <summary> /// 定义枚举 /// </summary> public enum ExpendRecordStatusEnum { /// <summary> /// 正常销售 /// </summary> [DisplayName("正常销售")] NormalSale = 4, /// <summary> /// 退换 /// </summary> [DisplayName("退换单据")] Replacement = 5 } /// <summary> /// 枚举帮助 /// </summary> public static class EnumHelper { /// <summary> /// 获得枚举量的DisplayName特性 /// </summary> /// <param name="eum"></param> /// <returns></returns> public static string GetDisplayName(this System.Enum eum) { var type = eum.GetType(); //先获取这个枚举的类型 var field = type.GetField(eum.ToString()); //通过这个类型获取到值 var obj = (DisplayNameAttribute)field.GetCustomAttribute(typeof(DisplayNameAttribute)); //得到特性 return obj.DisplayName ?? ""; } } /// <summary> /// 枚举测试类 /// </summary> public class TestEnum { /// <summary> /// 获取到字典描述值 /// </summary> /// <returns></returns> public string SearchEnumDisplayName() { return ExpendRecordStatusEnum.NormalSale.GetDisplayName(); } } }