using System.Reflection; namespace SafeCampus.Core.Extension { public static partial class Extensions { #region 枚举成员转成dictionary类型 /// /// 转成dictionary类型 /// /// /// public static Dictionary EnumToDictionary(this Type enumType) { Dictionary dictionary = new Dictionary(); Type typeDescription = typeof(DescriptionAttribute); FieldInfo[] fields = enumType.GetFields(); int sValue = 0; string sText = string.Empty; foreach (FieldInfo field in fields) { if (field.FieldType.IsEnum) { sValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)); object[] arr = field.GetCustomAttributes(typeDescription, true); if (arr.Length > 0) { DescriptionAttribute da = (DescriptionAttribute)arr[0]; sText = da.Description; } else { sText = field.Name; } dictionary.Add(sValue, sText); } } return dictionary; } /// /// 转成dictionary类型 /// /// /// public static List EnumToEnumModel(this Type enumType) { List dictionary = new List(); Type typeDescription = typeof(DescriptionAttribute); FieldInfo[] fields = enumType.GetFields(); int sValue = 0; string sText = string.Empty; foreach (FieldInfo field in fields) { if (field.FieldType.IsEnum) { sValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)); object[] arr = field.GetCustomAttributes(typeDescription, true); if (arr.Length > 0) { DescriptionAttribute da = (DescriptionAttribute)arr[0]; sText = da.Description; } dictionary.Add(new EnumModel() { Description = sText,Name = field.Name,Value = sValue }); } } return dictionary; } /// /// 枚举成员转成键值对Json字符串 /// /// /// public static string EnumToDictionaryString(this Type enumType) { List> dictionaryList = EnumToDictionary(enumType).ToList(); var sJson = JsonConvert.SerializeObject(dictionaryList); return sJson; } #endregion #region 获取枚举的描述 /// /// 获取枚举值对应的描述 /// /// /// public static string GetDescription(this System.Enum enumType) { FieldInfo EnumInfo = enumType.GetType().GetField(enumType.ToString()); if (EnumInfo != null) { DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (EnumAttributes.Length > 0) { return EnumAttributes[0].Description; } } return enumType.ToString(); } #endregion #region 根据值获取枚举的描述 public static string GetDescriptionByEnum(this object obj) { var tEnum = System.Enum.Parse(typeof(T), obj.ParseToString()) as System.Enum; var description = tEnum.GetDescription(); return description; } #endregion } public class EnumModel { /// /// 描述 /// public string Description { get; set; } /// /// 属性名 /// public string Name { get; set; } /// /// 枚举值 /// public int Value { get; set; } } }