ValueConverter.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. namespace Quadarax.Foundation.Core.Value
  2. {
  3. public static class ValueConverter
  4. {
  5. public static object ConvertTo(Type toType, string value)
  6. {
  7. if (string.IsNullOrEmpty(value)) return null;
  8. if (toType == typeof(string)) return (object)value;
  9. if (toType == typeof(int)) return (object)int.Parse(value);
  10. if (toType == typeof(long)) return (object)long.Parse(value);
  11. if (toType == typeof(bool)) return (object)bool.Parse(value);
  12. if (toType == typeof(double)) return (object)double.Parse(value);
  13. if (toType == typeof(float)) return (object)float.Parse(value);
  14. if (toType == typeof(decimal)) return (object)decimal.Parse(value);
  15. if (toType == typeof(byte)) return (object)byte.Parse(value);
  16. if (toType == typeof(sbyte)) return (object)sbyte.Parse(value);
  17. if (toType == typeof(short)) return (object)short.Parse(value);
  18. if (toType == typeof(ushort)) return (object)ushort.Parse(value);
  19. if (toType == typeof(uint)) return (object)uint.Parse(value);
  20. if (toType == typeof(ulong)) return (object)ulong.Parse(value);
  21. if (toType == typeof(char)) return (object)char.Parse(value);
  22. if (toType == typeof(Guid)) return (object)Guid.Parse(value);
  23. if (toType == typeof(TimeSpan)) return (object)TimeSpan.Parse(value);
  24. if (toType.IsEnum) return (object)Enum.Parse(toType, value, true);
  25. throw new NotSupportedException($"Cannot convert value to type '{toType}'. Not supported!");
  26. }
  27. public static TValue? ConvertTo<TValue>(string value)
  28. {
  29. return (TValue)ConvertTo(typeof(TValue), value);
  30. }
  31. }
  32. }