You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.6KB

  1. namespace HealthMonitor.Core.Common
  2. {
  3. public class StringHelper
  4. {
  5. private static Type TYPE_INT = typeof(int);
  6. private static Type TYPE_LONG = typeof(long);
  7. private static Type TYPE_FLOAT = typeof(float);
  8. private static Type TYPE_DOUBLE = typeof(double);
  9. private static Type TYPE_DECIMAL = typeof(decimal);
  10. private static Type TYPE_BOOLEAN = typeof(bool);
  11. public static object ConvertToType(string str, Type type)
  12. {
  13. //if (type.IsClass)
  14. //{
  15. // //引用类型,通过json反序列化转换
  16. // return JsonConvert.DeserializeObject(str, type);
  17. //}
  18. //if (!type.IsPrimitive && type.IsValueType)
  19. //{
  20. // //结构类型,通过json反序列化转换
  21. // return JsonConvert.DeserializeObject(str, type);
  22. //}
  23. if (type.IsPrimitive && type.IsValueType)
  24. {
  25. if (type == TYPE_INT) return int.TryParse(str, out int result) ? result : 0;
  26. if (type == TYPE_LONG) return long.TryParse(str, out long result) ? result : 0;
  27. if (type == TYPE_FLOAT) return float.TryParse(str, out float result) ? result : 0;
  28. if (type == TYPE_DOUBLE) return double.TryParse(str, out double result) ? result : 0;
  29. if (type == TYPE_DECIMAL) return decimal.TryParse(str, out decimal result) ? result : 0;
  30. if (type == TYPE_BOOLEAN) return bool.TryParse(str, out bool result) ? result : false;
  31. }
  32. return str;
  33. }
  34. }
  35. }