强制转化常用函数
1 { 2 #region 强制转化 3 /// <summary> 4 /// object转化为Bool类型 5 /// </summary> 6 /// <param name="obj"></param> 7 /// <returns></returns> 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 /// <summary> 22 /// object强制转化为DateTime类型(吃掉异常) 23 /// </summary> 24 /// <param name="obj"></param> 25 /// <returns></returns> 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 /// <summary> 42 /// int强制转化 43 /// </summary> 44 /// <param name="obj"></param> 45 /// <returns></returns> 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 /// <summary> 63 /// 强制转化为long 64 /// </summary> 65 /// <param name="obj"></param> 66 /// <returns></returns> 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 /// <summary> 84 /// 强制转化可空int类型 85 /// </summary> 86 /// <param name="obj"></param> 87 /// <returns></returns> 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 /// <summary> 101 /// 强制转化为string 102 /// </summary> 103 /// <param name="obj"></param> 104 /// <returns></returns> 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 /// <summary> 118 /// Decimal转化 119 /// </summary> 120 /// <param name="obj"></param> 121 /// <returns></returns> 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 try 133 { 134 return Convert.ToDecimal(obj); 135 } 136 catch 137 { 138 return 0M; 139 } 140 } 141 /// <summary> 142 /// Decimal可空类型转化 143 /// </summary> 144 /// <param name="obj"></param> 145 /// <returns></returns> 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 #endregion 159 160 }