zoukankan      html  css  js  c++  java
  • 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()];//输出“是”
  • 相关阅读:
    Linux 文件权限
    spak数据倾斜解决方案
    逻辑时钟
    kafka入门
    深入学习MySQL事务:ACID特性的实现原理
    程序员的诗
    java技术突破要点
    一个请求过来都经历了什么
    如何保持长时间高效学习
    你的系统如何支撑高并发
  • 原文地址:https://www.cnblogs.com/xinbaba/p/10400392.html
Copyright © 2011-2022 走看看