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 @   黄高林  阅读(480)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示