using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace CCompressorXN_HelperLib { /// /// 枚举操作类 /// public class EnumHelper { /// /// 根据值获取枚举方法 /// /// typeof(枚举) /// /// public static Enum GetEnumByValue(Type enumType, int value) { return Enum.Parse(enumType, Enum.GetName(enumType, value)) as Enum; } /// /// 获取枚举的Description /// /// /// 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 == null || objs.Length == 0) //当描述属性没有时,直接返回名称 return value; DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return descriptionAttribute.Description; } /// /// 字符串转Enum /// /// 枚举 /// 字符串 /// 转换的枚举 public static T ToEnum(string str) { return (T)Enum.Parse(typeof(T), str); } /// /// 枚举转集合 /// /// /// public static List GetEnumItems() { var result = new List(); Type enumType = typeof(T); if (!enumType.IsEnum) { return result; } string[] fieldstrs = Enum.GetNames(enumType); foreach (var item in fieldstrs) { var field = enumType.GetField(item); object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组 string description; if (arr != null && arr.Length > 0) { description = ((DescriptionAttribute)arr[0]).Description; //属性描述 } else { description = item; //描述不存在取字段名称 } result.Add(new EnumItem { Code = item, Value = (int)Enum.Parse(enumType, item), Descprtion = description, }); } return result; } /// /// 根据字符串获取枚举值 /// /// /// /// public static int ConvertEnumToInt(string name) { try { return (int)Enum.Parse(typeof(T), name); } catch (Exception) { throw; } } } public class EnumItem { /// /// 枚举值 /// public string Code { get; set; } public int Value { get; set; } /// /// 描述 /// public string Descprtion { get; set; } } }