stringExtensions.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Bowin.Common.Utility;
  6. namespace Bowin.Common.Linq
  7. {
  8. public static class stringExtensions
  9. {
  10. /// <summary>
  11. /// 把字符串转成对应该类型(自动去左右空格)
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. /// <param name="text"></param>
  15. /// <returns></returns>
  16. public static Nullable<T> ConvertLinqData<T>(this string text) where T : struct
  17. {
  18. text = text.Trim();
  19. var convertvalue = new Nullable<T>();
  20. if (text.Length > 0 || typeof(T) == typeof(string))
  21. {
  22. convertvalue = new Nullable<T>((T)Convert.ChangeType(text, typeof(T)));
  23. }
  24. return convertvalue;
  25. }
  26. public static object ParseToType(this string text, Type targetType)
  27. {
  28. text = text.Trim();
  29. var valueTargetType = targetType;
  30. if (valueTargetType.Name.StartsWith("Nullable")) valueTargetType = targetType.GetGenericArguments()[0];
  31. var converterType = typeof(WebExtensions);
  32. var converter = converterType.GetMethod("ParseTo", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
  33. converter = converter.MakeGenericMethod(valueTargetType);
  34. return converter.Invoke(null, new object[] { text });
  35. }
  36. }
  37. }