Fork me on GitHub

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个月的博客龄了,不过一直没有写博客,希望通过我们分享,能给有需要的朋友们带来帮助--------------

posted @ 2018-04-24 14:45  黄高林  阅读(468)  评论(0编辑  收藏  举报