using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace Transmission.SDK { public class EnumHelper { /// /// 获取变量名称 /// /// 变量 /// public static string GetVarName(Expression> exp) { return ((MemberExpression)exp.Body).Member.Name; } /// /// 获取枚举项描述信息 例如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(DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) return ((DescriptionAttribute)attrs[0]).Description; } return en.ToString(); } /// /// EnumToNameValueCollection /// ///Type,该参数的格式为typeof(需要读的枚举类型) ///键值对 public static NameValueCollection EnumToNVC(Type enumType) { NameValueCollection nvc = new NameValueCollection(); 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; } nvc.Add(strValue, strText); } } return nvc; } /// /// EnumToDictionary /// /// ///Dictionary枚举项,描述 public static Dictionary EnumToDictionary(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; } } }