EnumExtensionHelper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 NX_CommonClassLibrary
  9. {
  10. public static class EnumExtensionHelper
  11. {
  12. #region 根据枚举值返回枚举对象
  13. /// <summary>
  14. /// 根据枚举值返回枚举对象
  15. /// </summary>
  16. /// <typeparam name="T">枚举类型</typeparam>
  17. /// <param name="val">枚举值</param>
  18. /// <returns>返回指定的枚举类型对象</returns>
  19. public static T GetEnumObj<T>(object val) where T : Enum
  20. {
  21. FieldInfo[] fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
  22. bool isGet = false;
  23. foreach (var fi in fields)
  24. {
  25. int enumVal = ((int)fi.GetValue(null));
  26. int tmpVal = Convert.ToInt32(val);
  27. if (enumVal == tmpVal)
  28. {
  29. isGet = true;
  30. break;
  31. }
  32. }
  33. if (isGet)
  34. {
  35. val = Convert.ToInt32(val);
  36. return (T)val;
  37. }
  38. else
  39. {
  40. return (T)fields[0].GetValue(null);
  41. }
  42. }
  43. public static object GetEnumObj1(object val,Type t)
  44. {
  45. FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);
  46. bool isGet = false;
  47. foreach (var fi in fields)
  48. {
  49. int enumVal = ((int)fi.GetValue(null));
  50. int tmpVal = Convert.ToInt32(val);
  51. if (enumVal == tmpVal)
  52. {
  53. isGet = true;
  54. break;
  55. }
  56. }
  57. if (isGet)
  58. {
  59. val = Convert.ToInt32(val);
  60. return val;
  61. }
  62. else
  63. {
  64. return fields[0].GetValue(null);
  65. }
  66. }
  67. #endregion
  68. public static IEnumerable<KeyValuePair<int, string>> GetEnumDescription(Type type)
  69. {
  70. List<KeyValuePair<int, string>> result = new List<KeyValuePair<int, string>>();
  71. if (!type.IsEnum) return result;
  72. var fields = type.GetFields();
  73. foreach (var field in fields)
  74. {
  75. object[] attrs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
  76. if (null != attrs && attrs.Length > 0)
  77. {
  78. result.Add(new KeyValuePair<int, string>((int)field.GetRawConstantValue(), ((DescriptionAttribute)attrs[0]).Description));
  79. }
  80. }
  81. return result;
  82. }
  83. }
  84. }