C# .net 遍历枚举和特性(Attribute)
现在我们有一个枚举,我需要获取其枚举名称、值、Description,那么我们可以参照如下操作:
枚举:
////// 岗位审批状态 /// public enum PostApproveStatus : int { /// /// 待审核 /// [Description("待审核")] Wait = 0, /// /// 审核通过 /// [Description("审核通过")] Success = 1, /// /// 审核驳回 /// [Description("审核驳回")] Fail = 2 }
再来个获取所有信息的model
public class EnumInfo { ////// 枚举值 /// public int Value { get; set; } /// /// 枚举名 /// public string Name { get; set; } /// /// 特性 /// public string Description { get; set; } }
遍历枚举
////// 获取所有枚举 /// /// /// public static List GetAllEnums(this Type type) { var result = new List (); if (type.IsEnum) { var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public) ?? new FieldInfo[] { }; foreach (var field in fields) { var info = new EnumInfo(); info.Name = field.Name; info.Value = (int)field.GetValue(null); var atts = field.GetCustomAttributes(typeof(DescriptionAttribute), false); info.Description = atts != null && atts.Length > 0 ? ((DescriptionAttribute[])atts)[0].Description : string.Empty; result.Add(info); } } return result; }
调用方法:
var enumList = typeof(PostApproveStatus).GetAllEnums();
这时我们拿到的enumList就是一个EnumInfo的列表,我们就能通过这个列表拿到所有枚举值的所有信息啦。