using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSFrameworkV5.Core { /// /// 对象(字符串)转换常用扩展方法 /// public static class ExtensionMethods { public static string ToStringEx(this object o) { if (o == null) return string.Empty; return o.ToString(); //return o.ToString().Trim(); } public static bool IsNullOrEmpty(this object s) { return string.IsNullOrEmpty(s.ToStringEx()); } public static DateTime ToSqlDateTime(this string o) { var defMinValue = DateTime.Parse("1753-01-01 00:00:00"); var defMaxValue = DateTime.Parse("9999-12-31 23:59:59"); if (null == o) return defMinValue; //传入空值,返回预设值 DateTime dt; if (DateTime.TryParse(o.ToStringEx(), out dt)) { if (dt < defMinValue || dt > defMaxValue) return defMinValue; //无效日期,预设返回SQL支持的最小日期 else return dt; } return defMinValue; } public static float ToFloatEx(this string o) { if (null == o) return 0; try { return (float)Convert.ToDouble(o.ToStringEx()); } catch { return 0; } } public static int ToIntEx(this string o) { if (null == o) return 0; try { return Convert.ToInt32(o.ToStringEx()); } catch { return 0; } } public static decimal ToDecimalEx(this string o, int i = 2) { if (null == o) return 0; try { //Math.Round之后不自动补零 //return decimal.Parse(Math.Round(Convert.ToDouble(s.ToStringEx()), i).ToStringEx()); return decimal.Parse(Convert.ToDecimal(o.ToStringEx()) .ToString("F" + i)); } catch { return 0; } } } }