StringExtension.cs 614 B

12345678910111213141516171819202122232425262728293031
  1. using System;
  2. using System.ComponentModel;
  3. namespace HandyControl.Tools.Extension;
  4. public static class StringExtension
  5. {
  6. public static T Value<T>(this string input)
  7. {
  8. try
  9. {
  10. return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(input);
  11. }
  12. catch
  13. {
  14. return default;
  15. }
  16. }
  17. public static object Value(this string input, Type type)
  18. {
  19. try
  20. {
  21. return TypeDescriptor.GetConverter(type).ConvertFromString(input);
  22. }
  23. catch
  24. {
  25. return null;
  26. }
  27. }
  28. }