using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NCC.Code { /// /// 强制转化辅助类(无异常抛出) /// public static class ConvertHelper { #region 强制转化 /// /// object转化为Bool类型 /// /// /// public static bool ObjToBool(this object obj) { bool flag; if (obj == null) { return false; } if (obj.Equals(DBNull.Value)) { return false; } return (bool.TryParse(obj.ToString(), out flag) && flag); } /// /// object强制转化为DateTime类型(吃掉异常) /// /// /// public static DateTime? ObjToDateNull(this object obj) { if (obj == null) { return null; } try { return new DateTime?(Convert.ToDateTime(obj)); } catch (ArgumentNullException ex) { return null; } } /// /// int强制转化 /// /// /// public static int ObjToInt(this object obj) { try { if (obj != null) { int num; if (obj.Equals(DBNull.Value)) { return 0; } if (int.TryParse(obj.ToString(), out num)) { return num; } } } catch (Exception) { } return 0; } /// /// 强制转化为long /// /// /// public static long ObjToLong(this object obj) { if (obj != null) { long num; if (obj.Equals(DBNull.Value)) { return 0; } if (long.TryParse(obj.ToString(), out num)) { return num; } } return 0; } /// /// 强制转化可空int类型 /// /// /// public static int? ObjToIntNull(this object obj) { if (obj == null) { return null; } if (obj.Equals(DBNull.Value)) { return null; } return new int?(ObjToInt(obj)); } /// /// 强制转化为string /// /// /// public static string ObjToStr(this object obj) { if (obj == null) { return ""; } if (obj.Equals(DBNull.Value)) { return ""; } return Convert.ToString(obj); } /// /// Decimal转化 /// /// /// public static decimal ObjToDecimal(this object obj) { if (obj == null) { return 0M; } if (obj.Equals(DBNull.Value)) { return 0M; } try { return Convert.ToDecimal(obj); } catch { return 0M; } } /// /// Decimal可空类型转化 /// /// /// public static decimal? ObjToDecimalNull(this object obj) { if (obj == null) { return null; } if (obj.Equals(DBNull.Value)) { return null; } return new decimal?(ObjToDecimal(obj)); } /// /// 获取时间对应的周(中文) /// /// /// public static string DateTimeToWeekCN(this DateTime obj) { if (obj == null) { return null; } try { string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; string week = Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString(); return week; } catch (Exception) { return "未知"; } } #endregion } }