EnumHelper.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace IwbZero.ToolCommon.StringModel
  5. {
  6. public static class EnumHelper
  7. {
  8. /// <summary>
  9. /// 根据枚举的名称获取枚举
  10. /// </summary>
  11. /// <typeparam name="TEnum">枚举类型</typeparam>
  12. /// <param name="str">字符串</param>
  13. /// <returns></returns>
  14. public static TEnum GetEnumByName<TEnum>(this string str) where TEnum : struct
  15. {
  16. if (Enum.TryParse<TEnum>(str, out var result))
  17. {
  18. return result;
  19. }
  20. return default;
  21. }
  22. /// <summary>
  23. /// 根据枚举获取枚举值
  24. /// </summary>
  25. /// <typeparam name="TEnum">枚举类型</typeparam>
  26. /// <param name="e">枚举</param>
  27. /// <returns></returns>
  28. public static int ToInt<TEnum>(this TEnum e) where TEnum : struct
  29. {
  30. return Convert.ToInt32(e);
  31. }
  32. /// <summary>
  33. /// 根据枚举的值获取枚举名称
  34. /// </summary>
  35. /// <typeparam name="TEnum">枚举类型</typeparam>
  36. /// <param name="status">枚举的值</param>
  37. /// <returns></returns>
  38. public static string GetEnumName<TEnum>(this int status)
  39. {
  40. return Enum.GetName(typeof(TEnum), status);
  41. }
  42. /// <summary>
  43. /// 获取枚举名称集合
  44. /// </summary>
  45. /// <typeparam name="TEnum"></typeparam>
  46. /// <returns></returns>
  47. public static string[] GetNamesArr<TEnum>()
  48. {
  49. return Enum.GetNames(typeof(TEnum));
  50. }
  51. /// <summary>
  52. /// 将枚举转换成字典集合
  53. /// </summary>
  54. /// <typeparam name="TEnum">枚举类型</typeparam>
  55. /// <returns></returns>
  56. public static Dictionary<string, int> GetEnumDic<TEnum>()
  57. {
  58. Dictionary<string, int> resultList = new Dictionary<string, int>();
  59. Type type = typeof(TEnum);
  60. var strList = GetNamesArr<TEnum>().ToList();
  61. foreach (string key in strList)
  62. {
  63. string val = Enum.Format(type, Enum.Parse(type, key), "d");
  64. resultList.Add(key, int.Parse(val));
  65. }
  66. return resultList;
  67. }
  68. /// <summary>
  69. /// 将枚举转换成字典
  70. /// </summary>
  71. /// <typeparam name="TEnum"></typeparam>
  72. /// <returns></returns>
  73. public static Dictionary<string, int> GetDic<TEnum>()
  74. {
  75. Dictionary<string, int> dic = new Dictionary<string, int>();
  76. Type t = typeof(TEnum);
  77. var arr = Enum.GetValues(t);
  78. foreach (var item in arr)
  79. {
  80. dic.Add(item.ToString(), (int)item);
  81. }
  82. return dic;
  83. }
  84. }
  85. }