枚举帮助类

 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 }
View Code

 

转载于:https://www.cnblogs.com/missile/p/7607644.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值