public class MusterEnum { /// 获取枚举的描述信息 /// </summary> /// <param name="e">传入枚举对象</param> /// <returns>得到对应描述信息</returns> public String GetEnumDesc(Enum e) { FieldInfo EnumInfo = e.GetType().GetField(e.ToString()); if (EnumInfo == null) { return ""; } DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (EnumAttributes.Length > 0) { return EnumAttributes[0].Description; } return e.ToString(); } /// <summary> /// 将含有描述信息的枚举绑定到列表控件中 /// </summary> /// <param name="listControl"></param> /// <param name="enumType"></param> private Dictionary<string, string> BindDesEnumToListControl(System.Type enumType) { Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (object enumValue in Enum.GetValues(enumType)) { Enum e = (Enum)enumValue; dic.Add(((int)enumValue).ToString(), GetEnumDesc(e)); } return dic; } }
还有一个是根据传入的枚举的数字索引直接获取
public static string GetEnumDesc<T>(Object obj) { obj = (T)obj; if (obj == null) throw new ArgumentNullException("参数不能为null"); if (!obj.GetType().IsEnum) throw new Exception("参数类型不正确"); FieldInfo fieldinfo = obj.GetType().GetField(obj.ToString()); string str = string.Empty; Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (objs != null && objs.Length != 0) { DescriptionAttribute des = (DescriptionAttribute)objs[0]; str = des.Description; } return str; }
本文转自左正博客园博客,原文链接:http://www.cnblogs.com/soundcode/p/4846916.html
,如需转载请自行联系原作者