using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace SmartCoalApplication.Annotation.Enum { /// /// 枚举帮助类 /// public class EnumHelper { /// /// 获取枚举项描述信息 例如GetEnumDesc(Days.Sunday) /// /// 枚举项 如Days.Sunday /// public static string GetEnumDesc(System.Enum en) { Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) return ((DescriptionAttribute)attrs[0]).Description; } return en.ToString(); } /// /// 获取枚举项+描述 /// ///Type,该参数的格式为typeof(需要读的枚举类型) ///键值对 public static Dictionary GetEnumItemDesc(Type enumType) { Dictionary dic = new Dictionary(); FieldInfo[] fieldinfos = enumType.GetFields(); foreach (FieldInfo field in fieldinfos) { if (field.FieldType.IsEnum) { Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); dic.Add(field.Name, ((DescriptionAttribute)objs[0]).Description); } } return dic; } /// /// 获取枚举值+描述 /// ///Type,该参数的格式为typeof(需要读的枚举类型) ///键值对 public static Dictionary GetEnumItemValueDesc(Type enumType) { Dictionary dic = new Dictionary(); Type typeDescription = typeof(DescriptionAttribute); FieldInfo[] fields = enumType.GetFields(); string strText = string.Empty; string strValue = string.Empty; foreach (FieldInfo field in fields) { if (field.FieldType.IsEnum) { strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString(); object[] arr = field.GetCustomAttributes(typeDescription, true); if (arr.Length > 0) { DescriptionAttribute aa = (DescriptionAttribute)arr[0]; strText = aa.Description; } else { strText = field.Name; } dic.Add(strValue, strText); } } return dic; } } }