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

 1.首先定义一个枚举

    public enum State
    {
        [Description("")]
        Yes = 1,

        [Description("")]
        No = 0
    }

 2.添加拓展类

 

/// <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;
}

3.使用方法

State.YES.GetDescription()//输出“是”

NameValueCollection nvc = EnumDescriptionExtension.GetNVCFromEnumValue(typeof(State)); 

var resultmessage = nvc[1.ToString()];//输出“是”

 

posted @ 2019-02-19 12:59  吃辣椒的小毛驴  阅读(5128)  评论(0编辑  收藏  举报