完整代码在笔记结尾
获取枚举描述
public static string GetEnumDescription(this Enum en)
{
var type = en.GetType(); //获取类型
var memberInfos = type.GetMember(en.ToString()); //获取成员
if (memberInfos.Any())
{
if (memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attrs && attrs.Length > 0)
{
return attrs[0].Description; //返回当前描述
}
}
return en.ToString();
}
获取枚举Display特性的名称
原理与获取Description描述是一样的,都是先获取类型,再通过GetMember方法获取到每个成员到数组中,最后通过DisplayAttribute获取其属性,DisplayAttribute这个特性里面的属性可以在编写枚举成员时通过注解写入
[Display(Name = "红", GroupName = "纯色")]
[Description("红色")]
Red = 1,
[Display(Name = "橙红", GroupName = "混合色")]
[Description("橙红色")]
OriginRed = 2
获取Display特性下的属性的代码例子:
public static string GetDisplay(this Enum en)
{
var type = en.GetType(); //获取类型
var memberInfos = type.GetMember(en.ToString()); //获取成员
if (memberInfos.Any())
{
if (memberInfos[0].GetCustomAttributes(typeof(DisplayAttribute), false) is DisplayAttribute[] attrs && attrs.Length > 0)
{
//var groupName= attrs[0].GroupName;
//var order = attrs[0].Order;
return attrs[0].Name; //返回当前描述
}
}
return en.ToString();
}
获取枚举列表以枚举值作为Key
public static readonly ConcurrentDictionary<Type, Dictionary<int, string>> EnumNameValueDict = new ConcurrentDictionary<Type, Dictionary<int, string>>();
public static Dictionary<int, string> GetEnumDictionary(this Type enumType)
{
if (!enumType.IsEnum)
{
throw new Exception("传入的类型非枚举(Enum)类型");
}
var names = EnumNameValueDict.ContainsKey(enumType) ? EnumNameValueDict[enumType] : new Dictionary<int, string>();
if (names.Count == 0)
{
names = GetDictionaryItems(enumType);
EnumNameValueDict[enumType] = names;
}
return names;
}
根据枚举值获取枚举成员
public static string ToMemberByValue(this int value, Type enumType)
{
if (!enumType.IsEnum)
{
throw new Exception("给定的类型非枚举(Enum)类型");
}
var nvc = new NameValueCollection();
var fields = enumType.GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
nvc.Add(strValue, field.Name);
}
}
return nvc[value];
}
完整扩展类及使用示例
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace 枚举
{
/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
public static readonly ConcurrentDictionary<Type, Dictionary<int, string>> EnumNameValueDict = new ConcurrentDictionary<Type, Dictionary<int, string>>();
private static readonly ConcurrentDictionary<Type, Dictionary<string, int>> EnumValueNameDict = new ConcurrentDictionary<Type, Dictionary<string, int>>();
/// <summary>
/// 获取枚举对象Key与显示名称的字典
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <returns>以值为Key,显示名称为Value的字典</returns>
/// <exception cref="Exception">非枚举类型</exception>
public static Dictionary<int, string> GetEnumDictionary(this Type enumType)
{
if (!enumType.IsEnum)
{
throw new Exception("给定的类型非枚举(Enum)类型");
}
var names = EnumNameValueDict.ContainsKey(enumType) ? EnumNameValueDict[enumType] : new Dictionary<int, string>();
if (names.Count == 0)
{
names = GetDictionaryItems(enumType);
EnumNameValueDict[enumType] = names;
}
return names;
}
/// <summary>
/// 根据枚举成员获取自定义属性EnumDisplayNameAttribute的属性DisplayName
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<string, int> GetEnumDescriptionAndValue(this Type enumType)
{
return Enum.GetValues(enumType)
.Cast<object>()
.ToDictionary(e =>
GetEnumDescription(e as Enum),
e => (int)e);
}
/// <summary>
/// 获取枚举对象的值内容
/// </summary>
/// <param name="enumType"></param>
/// <param name="name"></param>
/// <returns></returns>
public static int GetEnumValue(this Type enumType, string name)
{
if (!enumType.IsEnum)
{
throw new Exception("给定的类型非枚举(Enum)类型");
}
Dictionary<string, int> enumDict = GetValueNameItems(enumType);
return enumDict.ContainsKey(name) ? enumDict[name] : enumDict.Select(d => d.Value).FirstOrDefault();
}
/// <summary>
/// 根据枚举成员获取Description描述
/// </summary>
/// <param name="en"></param>
/// <returns></returns>
public static string GetEnumDescription(this Enum en)
{
var type = en.GetType(); //获取类型
var memberInfos = type.GetMember(en.ToString()); //获取成员
if (memberInfos.Any())
{
if (memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) is DescriptionAttribute[] attrs && attrs.Length > 0)
{
return attrs[0].Description; //返回当前描述
}
}
return en.ToString();
}
/// <summary>
/// 根据枚举成员获取Display的属性Name
/// </summary>
/// <returns></returns>
public static string GetEnumDisplay(this Enum en)
{
var type = en.GetType(); //获取类型
var memberInfos = type.GetMember(en.ToString()); //获取成员
if (memberInfos.Any())
{
if (memberInfos[0].GetCustomAttributes(typeof(DisplayAttribute), false) is DisplayAttribute[] attrs && attrs.Length > 0)
{
return attrs[0].Name; //返回当前描述
}
}
return en.ToString();
}
/// <summary>
/// 根据枚举值获取枚举成员
/// </summary>
/// <param name="value">枚举值</param>
/// <param name="enumType">枚举类型</param>
/// <returns></returns>
public static string ToMemberByValue(this int value, Type enumType)
{
if (!enumType.IsEnum)
{
throw new Exception("给定的类型非枚举(Enum)类型");
}
var nvc = new NameValueCollection();
var fields = enumType.GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
nvc.Add(strValue, field.Name);
}
}
return nvc[value];
}
#region 私有操作方法
private static Dictionary<int, string> GetDictionaryItems(Type enumType)
{
var enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
var names = new Dictionary<int, string>(enumItems.Length);
foreach (FieldInfo enumItem in enumItems)
{
int intValue = (int)enumItem.GetValue(enumType);
names[intValue] = enumItem.Name;
}
return names;
}
private static Dictionary<string, int> GetValueNameItems(Type enumType)
{
var enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
var values = new Dictionary<string, int>(enumItems.Length);
foreach (var enumItem in enumItems)
{
values[enumItem.Name] = (int)enumItem.GetValue(enumType);
}
return values;
}
/// <summary>
/// 根据枚举类型得到其所有的 值 与 枚举定义字符串 的集合
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
private static NameValueCollection GetEnumStringFromEnumValue(Type enumType)
{
var nvc = new NameValueCollection();
var fields = enumType.GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
var strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
nvc.Add(strValue, field.Name);
}
}
return nvc;
}
#endregion
}
}
使用示例:
public class Program
{
static void Main(string[] args)
{
//使用示例:
var dic1 = typeof(MyEnum).GetEnumDictionary(); //获取所有成员
var dic2 = typeof(MyEnum).GetEnumDescriptionAndValue(); //获取所有成员(描述和值)
var memberVal = typeof(MyEnum).GetEnumValue("Red"); //根据成员字符串获取枚举值
var desc = MyEnum.Green.GetEnumDescription(); //根据枚举成员获取描述
var displayStr = MyEnum.Green.GetEnumDisplay(); //根据枚举成员获取显示名称
var member = 2.ToMemberByValue(typeof(MyEnum)); //根据枚举值获取枚举成员
}
public enum MyEnum
{
[Display(Name = "红", GroupName = "纯色")]
[Description("红色")]
Red = 1,
[Display(Name = "绿")]
[Description("绿色")]
Green = 2,
[Display(Name = "蓝")]
[Description("蓝色")]
Blue = 3,
}
}