1 { 2 #region 强制转化 3 ///4 /// object转化为Bool类型 5 /// 6 /// 7 ///8 public static bool ObjToBool(this object obj) 9 { 10 bool flag; 11 if (obj == null) 12 { 13 return false; 14 } 15 if (obj.Equals(DBNull.Value)) 16 { 17 return false; 18 } 19 return (bool.TryParse(obj.ToString(), out flag) && flag); 20 } 21 /// 22 /// object强制转化为DateTime类型(吃掉异常) 23 /// 24 /// 25 ///26 public static DateTime? ObjToDateNull(this object obj) 27 { 28 if (obj == null) 29 { 30 return null; 31 } 32 try 33 { 34 return new DateTime?(Convert.ToDateTime(obj)); 35 } 36 catch (ArgumentNullException ex) 37 { 38 return null; 39 } 40 } 41 /// 42 /// int强制转化 43 /// 44 /// 45 ///46 public static int ObjToInt(this object obj) 47 { 48 if (obj != null) 49 { 50 int num; 51 if (obj.Equals(DBNull.Value)) 52 { 53 return 0; 54 } 55 if (int.TryParse(obj.ToString(), out num)) 56 { 57 return num; 58 } 59 } 60 return 0; 61 } 62 /// 63 /// 强制转化为long 64 /// 65 /// 66 ///67 public static long ObjToLong(this object obj) 68 { 69 if (obj != null) 70 { 71 long num; 72 if (obj.Equals(DBNull.Value)) 73 { 74 return 0; 75 } 76 if (long.TryParse(obj.ToString(), out num)) 77 { 78 return num; 79 } 80 } 81 return 0; 82 } 83 /// 84 /// 强制转化可空int类型 85 /// 86 /// 87 ///88 public static int? ObjToIntNull(this object obj) 89 { 90 if (obj == null) 91 { 92 return null; 93 } 94 if (obj.Equals(DBNull.Value)) 95 { 96 return null; 97 } 98 return new int?(ObjToInt(obj)); 99 }100 /// 101 /// 强制转化为string102 /// 103 /// 104 ///105 public static string ObjToStr(this object obj)106 {107 if (obj == null)108 {109 return "";110 }111 if (obj.Equals(DBNull.Value))112 {113 return "";114 }115 return Convert.ToString(obj);116 }117 /// 118 /// Decimal转化119 /// 120 /// 121 ///122 public static decimal ObjToDecimal(this object obj)123 {124 if (obj == null)125 {126 return 0M;127 }128 if (obj.Equals(DBNull.Value))129 {130 return 0M;131 }132 try133 {134 return Convert.ToDecimal(obj);135 }136 catch137 {138 return 0M;139 }140 }141 /// 142 /// Decimal可空类型转化143 /// 144 /// 145 ///146 public static decimal? ObjToDecimalNull(this object obj)147 {148 if (obj == null)149 {150 return null;151 }152 if (obj.Equals(DBNull.Value))153 {154 return null;155 }156 return new decimal?(ObjToDecimal(obj));157 } 158 #endregion159 160 }