using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GpsCardGatewayPosition.Common { public class SafeType { /// <summary> /// Safes the int. /// </summary> /// <param name="o">The o.</param> /// <returns></returns> public static int SafeInt(object o) { var returnValue = 0; try { returnValue = Convert.ToInt32(o); } catch { returnValue = 0; } return returnValue; } /// <summary> /// Safes the int. /// </summary> /// <param name="o">The o.</param> /// <returns></returns> public static long SafeInt64(object o) { var returnValue = 0L; try { returnValue = Convert.ToInt64(o); } catch { returnValue = 0; } return returnValue; } /// <summary> /// Safes the string. /// </summary> /// <param name="o">The o.</param> /// <returns></returns> public static string SafeString(object o) { var returnValue = ""; try { returnValue = Convert.ToString(o); } catch { returnValue = ""; } return returnValue; } /// <summary> /// Safes the bool. /// </summary> /// <param name="o">The o.</param> /// <returns></returns> public static bool SafeBool(object o) { var returnValue = false; try { returnValue = Convert.ToBoolean(o); } catch { returnValue = false; } return returnValue; } public static double SafeDouble(object o) { double returnValue = 0; try { returnValue = Convert.ToDouble(o); } catch { returnValue = 0; } return returnValue; } /// <summary> /// Safes the decimal. /// </summary> /// <param name="o">The o.</param> /// <returns></returns> public static decimal SafeDecimal(object o) { var returnValue = 0.0M; try { returnValue = Convert.ToDecimal(o); } catch { returnValue = 0.0M; } return returnValue; } /// <summary> /// Safes the time. /// </summary> /// <param name="o">The o.</param> /// <returns></returns> public static DateTime SafeTime(object o) { var returnValue = DateTime.Parse("1900-01-01"); try { returnValue = Convert.ToDateTime(o); } catch { returnValue = DateTime.Parse("1900-01-01"); } return returnValue; } /// <summary> /// OBD时间转换 /// </summary> /// <param name="o"></param> /// <returns></returns> public static DateTime OBDSafeTime(object o) { var returnValue = DateTime.Parse("1900-01-01"); try { returnValue = Convert.ToDateTime(o); } catch { returnValue = DateTime.UtcNow; } return returnValue; } /// <summary> /// 是否为数字 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsNumber(string str) { int n; if (int.TryParse(str, out n)) { return true; } else { return false; } } } }