using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System
{
///
/// 字符串转换扩展
///
public static class SafeInputExtensions
{
///
/// 将字符串转换成Int类型,如果出错则返回0
///
///
///
public static short ToShort(this object str)
{
short result = 0;
if (str != null)
{
short.TryParse(str.ToString(), out result);
}
return result;
}
///
/// 将字符串转换成Int类型,如果出错则返回0
///
///
///
public static int ToInt(this object str)
{
int result = 0;
if (str != null)
{
int.TryParse(str.ToString(), out result);
}
return result;
}
///
/// 将字符串转换成decimal类型,如果出错则返回0
///
///
///
public static double ToDouble(this object str)
{
double result = 0.0;
if (str != null)
{
double.TryParse(str.ToString(), out result);
}
return result;
}
public static decimal ToDecimal(this object str)
{
decimal result = 0m;
if (str != null)
{
decimal.TryParse(str.ToString(), out result);
}
return result;
}
public static string ToNone(this object str, string extStr)
{
if (str != null && !string.IsNullOrEmpty(str.ToString()))
{
return str + " " + extStr;
}
return "";
}
///
/// 将字符串转换成真假
///
///
///
public static bool ToBool(this object str)
{
return str != null && str.ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
///
/// 将字符串转换成GUID,出错则为Guid.NewGuid()
///
///
///
public static Guid ToGuid(this object str)
{
Guid result = Guid.NewGuid();
if (str != null)
{
Guid.TryParse(str.ToString(), out result);
}
return result;
}
public static DateTime ToDateTime(this object str)
{
DateTime now = DateTime.Now;
if (str != null)
{
DateTime.TryParse(str.ToString(), out now);
}
return now;
}
public static string ToDateTimeRandom()
{
return DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(9999).ToString();
}
public static string ToDateString()
{
return DateTime.Now.ToString("yyyyMMdd");
}
public static string ToBr(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return str.Replace("\r\n", "
");
}
return str;
}
}
}