一、引用
1 using System.Collections.Generic;//键值对 2 using System.Reflection;//反射 3 System.ComponentModel;//指定属性
二、使用
1、返回枚举值的描述信息
1 /// <summary> 2 /// 返回枚举值的描述信息。 3 /// </summary> 4 /// <param name="value">要获取描述信息的枚举值。</param> 5 /// <returns>枚举值的描述信息。</returns> 6 public static string GetEnumDesc<T>(int value) 7 { 8 Type enumType = typeof(T); 9 DescriptionAttribute attr = null; 10 11 // 获取枚举常数名称。 12 string name = System.Enum.GetName(enumType, value); 13 if (name != null) 14 { 15 // 获取枚举字段。 16 FieldInfo fieldInfo = enumType.GetField(name); 17 if (fieldInfo != null) 18 { 19 // 获取描述的属性。 20 attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute; 21 22 } 23 } 24 25 // 返回结果 26 if (attr != null && !string.IsNullOrEmpty(attr.Description)) 27 return attr.Description; 28 else 29 return string.Empty; 30 }
2、返回枚举项的描述信息
1 /// <summary> 2 /// 返回枚举项的描述信息。 3 /// </summary> 4 /// <param name="e">要获取描述信息的枚举项。</param> 5 /// <returns>枚举项的描述信息。</returns> 6 public static string GetEnumDesc(System.Enum e) 7 { 8 if (e == null) 9 { 10 return string.Empty; 11 } 12 Type enumType = e.GetType(); 13 DescriptionAttribute attr = null; 14 15 // 获取枚举字段。 16 FieldInfo fieldInfo = enumType.GetField(e.ToString()); 17 if (fieldInfo != null) 18 { 19 // 获取描述的属性。 20 attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute; 21 } 22 23 // 返回结果 24 if (attr != null && !string.IsNullOrEmpty(attr.Description)) 25 return attr.Description; 26 else 27 return string.Empty; 28 }
3、获取枚举值列表,并转化为键值对
1 /// <summary> 2 /// 获取枚举值列表,并转化为键值对 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="isHasAll">是否包含“全部”</param> 6 /// <param name="filterItem">过滤项</param> 7 /// <returns></returns> 8 public static List<EnumKeyValue> EnumToList<T>(bool isHasAll, params string[] filterItem) 9 { 10 List<EnumKeyValue> list = new List<EnumKeyValue>(); 11 // 如果包含全部则添加 12 if (isHasAll) 13 { 14 list.Add(new EnumKeyValue() { Key = 0, Name = "全部" }); 15 } 16 foreach (int item in System.Enum.GetValues(typeof(T))) 17 { 18 string name = System.Enum.GetName(typeof(T), item); 19 // 跳过过滤项 20 if (filterItem != null) 21 { 22 if (Array.IndexOf<string>(filterItem, name) != -1) 23 { 24 continue; 25 } 26 } 27 // 添加 28 EnumKeyValue model = new EnumKeyValue(); 29 model.Key = item; 30 model.Name = name; 31 list.Add(model); 32 } 33 return list; 34 }
4、获取枚举的描述
/// <summary> /// 获取枚举的描述 /// </summary> /// <param name="value"></param> /// <returns></returns> public static string GetEnumDescription(this Enum value) { Type type = value.GetType(); string name = Enum.GetName(type, value); if (name != null) { // 获取枚举字段。 FieldInfo fieldInfo = type.GetField(name); if (fieldInfo != null) { // 获取描述的属性。 DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute; if (attr != null) { return attr.Description; } } } return null; }