前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >枚举帮助类

枚举帮助类

作者头像
用户6362579
发布2019-09-29 17:36:12
4950
发布2019-09-29 17:36:12
举报
文章被收录于专栏:小神仙小神仙
代码语言:javascript
复制
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Linq;
 5 
 6 namespace EnumHelper
 7 {
 8     /// <summary>
 9     /// 枚举帮助类
10     /// 1、获取枚举的描述文本
11     /// 2、获取枚举名和描述信息的列表
12     /// </summary>
13     public static class EnumHelper
14     {
15         /// <summary>
16         /// 获取枚举值的描述文本
17         /// </summary>
18         /// <param name="e">枚举值</param>
19         /// <returns></returns>
20         public static string Description(this System.Enum e)
21         {
22             Type enumType = e.GetType();
23             var name = Enum.GetName(enumType, e);
24             string des = GetDescription(enumType, name);
25             return des;
26         }
27 
28         /// <summary>
29         /// 获取枚举名和描述信息的列表
30         /// </summary>
31         /// <typeparam name="T">枚举类型</typeparam>
32         /// <param name="EnumType">类型</param>
33         /// <returns>枚举名和描述信息键值对</returns>
34         public static Dictionary<T, string> GetEnumAndDescription<T>(this Type EnumType) where T : struct
35         {
36             if (!EnumType.IsEnum)
37                 throw new ArgumentException("GetEnumValues: Type '" + EnumType.Name + "'不是枚举类型");
38 
39             Dictionary<T, string> dic = new Dictionary<T, string>();
40             foreach (var item in Enum.GetNames(EnumType))
41             {
42                 var _enum = (T)Enum.Parse(EnumType, item);
43                 var des = GetDescription(EnumType, item);
44                 dic.Add(_enum, des);
45             }
46             return dic;
47         }
48 
49         /// <summary>
50         /// 获取枚举名的描述文本
51         /// </summary>
52         /// <param name="enumType">类型</param>
53         /// <param name="name">枚举名</param>
54         /// <returns>描述文本</returns>
55         private static string GetDescription(Type enumType, string name)
56         {
57             string des = string.Empty;
58             var fieldInfo = enumType.GetFields().FirstOrDefault(a => a.Name == name);
59             object[] obj = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
60             if (obj.Length > 0)
61             {
62                 des = ((DescriptionAttribute)obj[0]).Description;
63             }
64             return des;
65         }
66     }
67 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-09-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档