|
1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- namespace HealthMonitor.Core.Common
- {
- public class StringHelper
- {
- private static Type TYPE_INT = typeof(int);
- private static Type TYPE_LONG = typeof(long);
- private static Type TYPE_FLOAT = typeof(float);
- private static Type TYPE_DOUBLE = typeof(double);
- private static Type TYPE_DECIMAL = typeof(decimal);
- private static Type TYPE_BOOLEAN = typeof(bool);
-
- public static object ConvertToType(string str, Type type)
- {
- //if (type.IsClass)
- //{
- // //引用类型,通过json反序列化转换
- // return JsonConvert.DeserializeObject(str, type);
- //}
-
- //if (!type.IsPrimitive && type.IsValueType)
- //{
- // //结构类型,通过json反序列化转换
- // return JsonConvert.DeserializeObject(str, type);
- //}
-
- if (type.IsPrimitive && type.IsValueType)
- {
- if (type == TYPE_INT) return int.TryParse(str, out int result) ? result : 0;
-
- if (type == TYPE_LONG) return long.TryParse(str, out long result) ? result : 0;
-
- if (type == TYPE_FLOAT) return float.TryParse(str, out float result) ? result : 0;
-
- if (type == TYPE_DOUBLE) return double.TryParse(str, out double result) ? result : 0;
-
- if (type == TYPE_DECIMAL) return decimal.TryParse(str, out decimal result) ? result : 0;
-
- if (type == TYPE_BOOLEAN) return bool.TryParse(str, out bool result) ? result : false;
- }
-
- return str;
- }
- }
- }
|