c# 根据Key或Value获取枚举描述

StatusCode.OK.GetDescription()

NameValueCollection nvc = EnumDescriptionExtension.GetNVCFromEnumValue(typeof(CheckFaceResultCode));
var resultmessage = nvc[HeadResultdata.code.ToString()];

/// <summary>
/// 根据Key获取枚举描述
/// </summary>
/// <param name="en"></param>
/// <returns></returns>
public static string GetDescription(this 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();
}
/// <summary>
/// 根据枚举类型得到其所有的 值 与 枚举定义Description属性 的集合
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static NameValueCollection GetNVCFromEnumValue(Type enumType)
{
NameValueCollection nvc = new NameValueCollection();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.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 = "";
}
nvc.Add(strValue, strText);
}
}
return nvc;
}

猜你喜欢

转载自www.cnblogs.com/xinbaba/p/10400392.html