IConvertibleExtensions.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Globalization;
  3. namespace Masuit.Tools
  4. {
  5. public static class IConvertibleExtensions
  6. {
  7. /// <summary>
  8. /// 类型直转
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. /// <param name="value"></param>
  12. /// <returns></returns>
  13. public static T ConvertTo<T>(this IConvertible value) where T : IConvertible
  14. {
  15. return (T)ConvertTo(value, typeof(T));
  16. }
  17. /// <summary>
  18. /// 类型直转
  19. /// </summary>
  20. /// <typeparam name="T"></typeparam>
  21. /// <param name="value"></param>
  22. /// <param name="defaultValue">转换失败的默认值</param>
  23. /// <returns></returns>
  24. public static T TryConvertTo<T>(this IConvertible value, T defaultValue = default) where T : IConvertible
  25. {
  26. try
  27. {
  28. return (T)ConvertTo(value, typeof(T));
  29. }
  30. catch
  31. {
  32. return defaultValue;
  33. }
  34. }
  35. /// <summary>
  36. /// 类型直转
  37. /// </summary>
  38. /// <typeparam name="T"></typeparam>
  39. /// <param name="value"></param>
  40. /// <param name="result">转换失败的默认值</param>
  41. /// <returns></returns>
  42. public static bool TryConvertTo<T>(this IConvertible value, out T result) where T : IConvertible
  43. {
  44. try
  45. {
  46. result = (T)ConvertTo(value, typeof(T));
  47. return true;
  48. }
  49. catch
  50. {
  51. result = default;
  52. return false;
  53. }
  54. }
  55. /// <summary>
  56. /// 类型直转
  57. /// </summary>
  58. /// <param name="value"></param>
  59. /// <param name="type">目标类型</param>
  60. /// <param name="result">转换失败的默认值</param>
  61. /// <returns></returns>
  62. public static bool TryConvertTo(this IConvertible value, Type type, out object result)
  63. {
  64. try
  65. {
  66. result = ConvertTo(value, type);
  67. return true;
  68. }
  69. catch
  70. {
  71. result = default;
  72. return false;
  73. }
  74. }
  75. /// <summary>
  76. /// 类型直转
  77. /// </summary>
  78. /// <param name="value"></param>
  79. /// <param name="type">目标类型</param>
  80. /// <returns></returns>
  81. public static object ConvertTo(this IConvertible value, Type type)
  82. {
  83. if (null == value)
  84. {
  85. return default;
  86. }
  87. if (type.IsEnum)
  88. {
  89. return Enum.Parse(type, value.ToString(CultureInfo.InvariantCulture));
  90. }
  91. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
  92. {
  93. var underlyingType = Nullable.GetUnderlyingType(type);
  94. return underlyingType!.IsEnum ? Enum.Parse(underlyingType, value.ToString(CultureInfo.CurrentCulture)) : Convert.ChangeType(value, underlyingType);
  95. }
  96. return Convert.ChangeType(value, type);
  97. }
  98. }
  99. }