C#.NET 对象(字符串)转换常用扩展方法
C#.NET 对象(字符串)转换常用扩展方法
C# Code:
/// <summary>
/// 对象(字符串)转换常用扩展方法
/// </summary>
public static class ExtensionMethods
{
public static string ToStringEx(this string str)
{
if (str == null) return "";
return str.ToString().Trim(); //.Replace(" ", "");
}
public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s.ToStringEx());
}
public static DateTime ToSqlDateTime(this string o)
{
DateTime defMinValue = DateTime.Parse("1753-01-01 00:00:00");
DateTime defMaxValue = DateTime.Parse("9999-12-31 23:59:59");
if (null == o) return defMinValue;//传入空值,返回预设值
DateTime dt;
if (DateTime.TryParse(o.ToString(), 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.ToString());
}
catch { return 0; }
}
public static int ToIntEx(this string o)
{
if (null == o) return 0;
try
{
return Convert.ToInt32(o.ToString());
}
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.ToString()), i).ToString());
return decimal.Parse(Convert.ToDecimal(o.ToString()).ToString("F" i));
}
catch { return 0; }
}
}
//来源:C/S框架网(www.csframework.com) QQ:1980854898
/// <summary>
/// 对象(字符串)转换常用扩展方法
/// </summary>
public static class ExtensionMethods
{
public static string ToStringEx(this string str)
{
if (str == null) return "";
return str.ToString().Trim(); //.Replace(" ", "");
}
public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s.ToStringEx());
}
public static DateTime ToSqlDateTime(this string o)
{
DateTime defMinValue = DateTime.Parse("1753-01-01 00:00:00");
DateTime defMaxValue = DateTime.Parse("9999-12-31 23:59:59");
if (null == o) return defMinValue;//传入空值,返回预设值
DateTime dt;
if (DateTime.TryParse(o.ToString(), 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.ToString());
}
catch { return 0; }
}
public static int ToIntEx(this string o)
{
if (null == o) return 0;
try
{
return Convert.ToInt32(o.ToString());
}
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.ToString()), i).ToString());
return decimal.Parse(Convert.ToDecimal(o.ToString()).ToString("F" i));
}
catch { return 0; }
}
}
//来源:C/S框架网(www.csframework.com) QQ:1980854898
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网