C# .net 遍历枚举和特性(Attribute)
现在我们有一个枚举,我需要获取其枚举名称、值、Description,那么我们可以参照如下操作:
枚举:
/// <summary> /// 岗位审批状态 /// </summary> public enum PostApproveStatus : int { /// <summary> /// 待审核 /// </summary> [Description("待审核")] Wait = 0, /// <summary> /// 审核通过 /// </summary> [Description("审核通过")] Success = 1, /// <summary> /// 审核驳回 /// </summary> [Description("审核驳回")] Fail = 2 }
再来个获取所有信息的model
public class EnumInfo { /// <summary> /// 枚举值 /// </summary> public int Value { get; set; } /// <summary> /// 枚举名 /// </summary> public string Name { get; set; } /// <summary> /// 特性 /// </summary> public string Description { get; set; } }
遍历枚举
/// <summary> /// 获取所有枚举 /// </summary> /// <param name="type"></param> /// <returns></returns> public static List<EnumInfo> GetAllEnums(this Type type) { var result = new List<EnumInfo>(); 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的列表,我们就能通过这个列表拿到所有枚举值的所有信息啦。