public class TypeHelper
{
#region 转Int
///<summary>
///将string类型转换为interesting类型
///<summary>
///<param name="s">目标字符串</param>
/// <param name="defaultValue">默认值</param>
public static int StringToInt(string s,int defaultValue)
{
//如果传入的字符串不是空
if(!string.IsNullOrWhiteSpace(s))
{
int result;
//将数字的字符串转换为与他等效的32位有符号整数,成功返回true
if(int.TryParse(s,out result))
return result;
}
return defaultValue;
}
public static int StringToInt(string s)
{
return StringToInt(s,0);
}
public static int ObjectToInt(object o,int defaultValue)
{
if(o!=null)
{
return StringToInt(o.ToString(),defaultValue);
}
return defaultValue;
}
public static int ObjectToInt(object o)
{
return ObjectToInt(o,0);
}
#endregion
#region转bool
public static bool StringToBool(string s,bool defaultValue)
{
if(s=="false")
return false;
else if(s=="true")
return true;
return defaultValue;
}
public static bool ToBool(string s)
{
return StringToBool(s,false);
}
public static bool ObjectToBool(object o,bool defaultValue)
{
if(o!=null)
return StringToBool(o.ToString(),defaultValue);
return defaultValue;
}
public static bool ObjectToBool(object o)
{
return ObjectToBool(o,false);
}
#endregion
#region转DateTime
public static DateTime StringToDateTime(string s,DateTime defaultValue)
{
if(!string.IsNullOrWhiteSpace(s))
{
DateTime result;
if(DateTime.TryParse(s,out result))
return result;
}
return defaultValue;
}
public static DateTime StringToDateTime(string s)
{
return StringToDateTime(s,DateTime.Now);
}
public static DateTime ObjectToDateTime(object o,DateTime defaultValue)
{
if(o!=null)
{
return StringToDateTime(o.Tostring(),defaultValue)
}
return defaultValue;
}
public static DateTiem ObjectToDateTime(object o)
{
return ObjectToDateTime(o,DateTime.Now);
}
#endregion
#region
public static DateTime ObjectToDecimal(string s,decimal defaultValue)
{
if(!string.IsNullOrWhiteSpace(s))
{
decimal result;
if(decimal.TryParse(s,out result))
return result;
}
return defaultValue;
}
public static decimal StringToDecimal(string s)
{
return StringToDecimal(s, 0m);
}
public static decimal ObjectToDecimal(object o, decimal defaultValue)
{
if (o != null)
return StringToDecimal(o.ToString(), defaultValue);
return defaultValue;
}
public static decimal ObjectToDecimal(object o)
{
return ObjectToDecimal(o, 0m);
}
#endregion
}
类型帮助类TypeHelper
猜你喜欢
转载自blog.csdn.net/qq_40098572/article/details/84617104
今日推荐
周排行