EmunHelper.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace wispro.sp.utility
  9. {
  10. public class EmunHelper
  11. {
  12. ///// <summary>
  13. ///// 根据枚举的值获取枚举名称
  14. ///// </summary>
  15. ///// <typeparam name="T">枚举类型</typeparam>
  16. ///// <param name="status">枚举的值</param>
  17. ///// <returns></returns>
  18. //public static string GetEnumName<T>(this int status)
  19. //{
  20. // return Enum.GetName(typeof(T), status);
  21. //}
  22. /// <summary>
  23. /// 获取枚举名称集合
  24. /// </summary>
  25. /// <typeparam name="T"></typeparam>
  26. /// <returns></returns>
  27. public static string[] GetNamesArr<T>()
  28. {
  29. return Enum.GetNames(typeof(T));
  30. }
  31. /// <summary>
  32. /// 将枚举转换成描述字典集合
  33. /// </summary>
  34. /// <typeparam name="T">枚举类型</typeparam>
  35. /// <returns></returns>
  36. public static Dictionary<string, T> getEnumDescriptionDic<T>()
  37. {
  38. Dictionary<string, T> resultList = new Dictionary<string, T>();
  39. Type type = typeof(T);
  40. var strList = GetNamesArr<T>().ToList();
  41. foreach (string key in strList)
  42. {
  43. var obj = (T)Enum.Parse(type, key);
  44. FieldInfo field= obj.GetType().GetField(obj.ToString());
  45. DescriptionAttribute att = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false) as DescriptionAttribute;
  46. if (att == null)
  47. {
  48. resultList.Add(key, obj);
  49. }
  50. else
  51. {
  52. resultList.Add(att.Description, obj);
  53. }
  54. }
  55. return resultList;
  56. }
  57. /// <summary>
  58. /// 将枚举转换成字典
  59. /// </summary>
  60. /// <typeparam name="TEnum"></typeparam>
  61. /// <returns></returns>
  62. public static Dictionary<string, int> GetDic<TEnum>()
  63. {
  64. Dictionary<string, int> dic = new Dictionary<string, int>();
  65. Type t = typeof(TEnum);
  66. var arr = Enum.GetValues(t);
  67. foreach (var item in arr)
  68. {
  69. dic.Add(item.ToString(), (int)item);
  70. }
  71. return dic;
  72. }
  73. }
  74. }