zoukankan      html  css  js  c++  java
  • C#实现枚举的相关操作

    枚举中的Descript()描述值,以及枚举值是一种一一对应的关系。我们可以获取其描述值和枚举值,存放到字典中,

    在实际的使用中我们就可以轻松的根据枚举值来获取其描述值,也可以通过枚举的描述值来获取其枚举值。

    根据枚举值来获取其描述值如下:

            /// <summary>
            /// 根据枚举值来获取描述信息
            /// </summary>
            /// <param name="e">枚举值</param>
            /// <returns></returns>
            public static string GetEnumDesc(Enum e)
            {
                DescriptionAttribute[] descAttribute = (DescriptionAttribute[])e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
                return descAttribute == null || descAttribute.Length == 0 ? string.Empty : descAttribute[0].Description;
            }

    但是这种方法是比较单一的,只能根据一个枚举值来获取一个描述信息。

    以下便可以实现获取所有的枚举值和秒速信息

     /// <summary>        

    /// 根据枚举类型来获取枚举值和枚举描述信息        

    /// </summary>        

    /// <typeparam name="T"></typeparam>        

    /// <returns></returns>        

    public static Dictionary<int, string> GetValueAndDesc<T>()         {

                Dictionary<int, string> dic = new Dictionary<int, string>();            

    try            

    {                

    foreach (FieldInfo item in typeof(T).GetFields())                

    {                   

      if (item.FieldType.IsEnum)                 

        {               

              int key = (int)typeof(T).InvokeMember(item.Name, BindingFlags.GetField, null, null, null);                

             DescriptionAttribute[] descs = (DescriptionAttribute[])item.GetCustomAttributes(typeof(DescriptionAttribute), false);             

                if (descs.Length > 0 && !dic.ContainsKey(key))                

             {                          

                        dic.Add(key, descs[0].Description);                

             }               

          }          

           }         

        }          

       catch (Exception)        

         {                // throw;             }       

          return dic;

    }

    这样之后我们可以轻松的通过键值对来轻松的获取我们先要的值或者描述信息。

    ------------------------哇!我这都三年5个月的博客龄了,不过一直没有写博客,希望通过我们分享,能给有需要的朋友们带来帮助--------------

  • 相关阅读:
    干货—MySQL常见的面试题+索引原理分析!
    如何设计一个百万级的消息推送系统
    【金三银四跳槽季】Java工程师如何在1个月内做好面试准备?
    Nginx实现请求的负载均衡 + keepalived实现Nginx的高可用
    java函数式编程之Supplier
    SpringMVC + MyBatis + Mysql + Redis(作为二级缓存) 配置
    Redis创建集群报错
    阿里云服务器Tomcat无法从外部访问
    SSM框架学习之高并发秒杀业务--笔记5-- 并发优化
    在windows上部署使用Redis
  • 原文地址:https://www.cnblogs.com/hglSV/p/BigHGL.html
Copyright © 2011-2022 走看看