定义枚举类型:
internal enum SexEnum { [Description("男性")] Man=1, [Description("女性")] Woman =2, [Description("未知")] Unknown =3, TestNoDescription=4 }
枚举扩展方法:
////// 枚举的扩展辅助操作方法 ///public static class EnumExtensions { /// /// 获取枚举项上的特性的文字描述 /// /// /// public static string ToDescription(this Enum value) { var type = value.GetType(); var member = type.GetMember(value.ToString()).FirstOrDefault(); return member != null ? member.ToDescription() : value.ToString(); } /// /// 获取成员元数据的Description特性描述信息 /// ///成员元数据对象 ///是否搜索成员的继承链以查找描述特性 ///返回Description特性描述信息,如不存在则返回成员的名称 public static string ToDescription(this MemberInfo member, bool inherit = false) { var desc = member.GetAttribute(inherit); return desc == null ? member.Name : desc.Description; } /// /// 从类型成员获取指定Attribute特性 /// ///Attribute特性类型 ///类型类型成员 ///是否从继承中查找 ///存在返回第一个,不存在返回null public static T GetAttribute(this MemberInfo memberInfo, bool inherit = false) where T : Attribute { var descripts = memberInfo.GetCustomAttributes(typeof(T), inherit); //获取第一个DescriptionAttribute return descripts.FirstOrDefault() as T; } }
获得枚举信息:
Listresult = new List(); var list = Enum.GetValues(typeof(SexEnum)).Cast(); Console.WriteLine($"枚举结果如下:"); foreach (var item in list) { var info = new EnumInfo() { Name = item.ToString(), Value = (int)item, Description = item.ToDescription() }; result.Add(info); Console.WriteLine($"Name:{info.Name},Value:{info.Value},Description:{info.Description}"); }
泛型方法:
public static ListGetEnumList() where T : Enum { var type = typeof(T); Listresult = new List(); var list = Enum.GetValues(type).Cast(); foreach (var item in list) { var info = new EnumInfo() { Name = item.ToString(), Value = (int)Convert.ChangeType(item, typeof(int)), Description = item.ToDescription() }; result.Add(info); } return result; }
EnumInfo类
public class EnumInfo { public string Name { get; set; } public short Value { get; set; } public string Description { get; set; } }