代码:
public class EnumberHelper { public static List<EnumberEntity> EnumToList<T>() { List<EnumberEntity> list = new List<EnumberEntity>(); foreach (var e in Enum.GetValues(typeof(T))) { EnumberEntity m = new EnumberEntity(); object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true); if(objArr!=null && objArr.Length>0) { DescriptionAttribute da = objArr[0] as DescriptionAttribute; m.Desction = da.Description; } m.EnumValue = Convert.ToInt32(e); m.EnumName = e.ToString(); list.Add(m); } return list; } } public class EnumberEntity { /// <summary> /// 枚举的描述 /// </summary> public string Desction { set; get; } /// <summary> /// 枚举名称 /// </summary> public string EnumName { set; get; } /// <summary> /// 枚举对象的值 /// </summary> public int EnumValue { set; get; } }
枚举:
public enum QxItem { [Description("查看")] Show = 0, [Description("新增")] Add = 1, [Description("编辑")] Edit = 2, }
获取描述:
/// <summary> /// 获取枚举的描述 /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetEnumDescription(Enum enumValue) { string value = enumValue.ToString(); FieldInfo field = enumValue.GetType().GetField(value); //获取描述属性 object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //当描述属性没有时,直接返回名称 if (objs.Length == 0) { return value; } DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return descriptionAttribute.Description; }
另外一种:http://www.cnblogs.com/wenjian/archive/2009/06/19/1506550.html