using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Common.TextUtil { public static class SimpleTypeExtensions { /// /// 验证字符串是否是Null或者空字符串 /// /// /// public static bool IsEmptyOrNull(this string str) { if (str == null) { return true; } else if (str == "") { return true; } return false; } /// /// 转换字符串到32位整形 /// /// /// public static int ToInt32(this string str) { int rs = 0; if (int.TryParse(str, out rs)) { return rs; } throw new Exceptions.CannotConvertException(str); } /// /// 转换字符串到64位整形 /// /// /// public static long ToInt64(this string str) { long rs = 0; if (long.TryParse(str, out rs)) { return rs; } throw new Exceptions.CannotConvertException(str); } /// /// 转换字符串到16位整形 /// /// /// public static short ToInt16(this string str) { short rs = 0; if (short.TryParse(str, out rs)) { return rs; } throw new Exceptions.CannotConvertException(str); } /// /// 转换字符串到浮点型 /// /// /// public static decimal ToDecimal(this string str) { decimal rs = 0; if (decimal.TryParse(str, out rs)) { return rs; } throw new Exceptions.CannotConvertException(str); } /// /// 转换字符串到单精度浮点型 /// /// /// public static Single ToSingle(this string str) { Single rs = 0; if (Single.TryParse(str, out rs)) { return rs; } throw new Exceptions.CannotConvertException(str); } /// /// 转换字符串到双精度浮点型 /// /// /// public static double ToDouble(this string str) { double rs = 0; if (double.TryParse(str, out rs)) { return rs; } throw new Exceptions.CannotConvertException(str); } /// /// 转换字符串到布尔值,只支持0;1或者True;False,不区分大小写 /// /// /// public static bool ToBool(this string str) { if (str == "0" || str.ToUpper() == "FALSE") { return false; } else if (str == "1" || str.ToUpper() == "TRUE") { return true; } else { throw new Exceptions.CannotConvertException(str); } } /// /// 获取字符串值,如果为空则返回空字符串,过滤%和' /// /// /// public static string GetValue(this string str) { if (str == null) { return ""; } return str.Replace("'", "‘").Replace("%", "%"); } } }