ValueConverter.cs 1.8 KB

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