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.使用方法

StatusCode.OK.GetDescription()//输出“是”

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

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM