用法:

  1. var int1 = "2".TryToInt();//转换为int失败返回0
  2. var int2 = "2x".TryToInt();
  3. var int3 = "2".TryToInt(1);//转换为int失败返回1
  4. var int4 = "2x".TryToInt(1);
  5.  
  6. var d1 = "2".TryToMoney(); //同上
  7. var d2 = "2x".TryToMoney();
  8. var d3 = "2".TryToMoney(1);
  9. var d4 = "2x".TryToMoney(1);
  10.  
  11. string a = null;
  12. var s1 = a.TryToString();
  13. var s3 = a.TryToString("1");
  14.  
  15. var d11 = "2".TryToDecimal();
  16. var d22 = "2x".TryToDecimal();
  17. var d33 = "2".TryToDecimal(1);
  18. var d44 = "2x".TryToDecimal(1);
  19.  
  20. var de1 = "2013-1-1".TryToDate();
  21. var de2 = "x2013-1-1".TryToDate();
  22. var de3 = "x2013-1-1".TryToDate(DateTime.Now);
  23.  
  24. //json和model转换
  25. var json = new { id = 1 }.ModelToJson();
  26. var model = "{id:1}".JsonToModel<ModelTest>();
  27.  
  28. //list和dataTable转换
  29. var dt = new List<ModelTest>().ListToDataTable();
  30. var list = dt.DataTableToList<ModelTest>();

  

代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.Script.Serialization;
  6. using System.Data;
  7. using System.Reflection;
  8. using System.Collections;
  9.  
  10. namespace SyntacticSugar
  11. {
  12. /// <summary>
  13. /// ** 描述:类型转换
  14. /// ** 创始时间:2015-6-2
  15. /// ** 修改时间:-
  16. /// ** 作者:sunkaixuan
  17. /// ** 使用说明:
  18. /// </summary>
  19. public static class TypeParseExtenions
  20. {
  21. #region 强转成int 如果失败返回 0
  22. /// <summary>
  23. /// 强转成int 如果失败返回 0
  24. /// </summary>
  25. /// <param name="thisValue"></param>
  26. /// <param name="i"></param>
  27. /// <returns></returns>
  28. public static int TryToInt(this object thisValue)
  29. {
  30. int reval = 0;
  31. if (thisValue != null && int.TryParse(thisValue.ToString(), out reval))
  32. {
  33. return reval;
  34. }
  35. return reval;
  36. }
  37. #endregion
  38. #region 强转成int 如果失败返回 errorValue
  39. /// <summary>
  40. /// 强转成int 如果失败返回 errorValue
  41. /// </summary>
  42. /// <param name="thisValue"></param>
  43. /// <param name="i"></param>
  44. /// <returns></returns>
  45. public static int TryToInt(this object thisValue, int errorValue)
  46. {
  47. int reval = 0;
  48. if (thisValue != null && int.TryParse(thisValue.ToString(), out reval))
  49. {
  50. return reval;
  51. }
  52. return errorValue;
  53. }
  54. #endregion
  55. #region 强转成double 如果失败返回 0
  56. /// <summary>
  57. /// 强转成money 如果失败返回 0
  58. /// </summary>
  59. /// <param name="thisValue"></param>
  60. /// <param name="i"></param>
  61. /// <returns></returns>
  62. public static double TryToMoney(this object thisValue)
  63. {
  64. double reval = 0;
  65. if (thisValue != null && double.TryParse(thisValue.ToString(), out reval))
  66. {
  67. return reval;
  68. }
  69. return 0;
  70. }
  71. #endregion
  72. #region 强转成double 如果失败返回 errorValue
  73. /// <summary>
  74. /// 强转成double 如果失败返回 errorValue
  75. /// </summary>
  76. /// <param name="thisValue"></param>
  77. /// <param name="errorValue"></param>
  78. /// <returns></returns>
  79. public static double TryToMoney(this object thisValue, int errorValue)
  80. {
  81. double reval = 0;
  82. if (thisValue != null && double.TryParse(thisValue.ToString(), out reval))
  83. {
  84. return reval;
  85. }
  86. return errorValue;
  87. }
  88. #endregion
  89. #region 强转成string 如果失败返回 ""
  90. /// <summary>
  91. /// 强转成string 如果失败返回 ""
  92. /// </summary>
  93. /// <param name="thisValue"></param>
  94. /// <param name="i"></param>
  95. /// <returns></returns>
  96. public static string TryToString(this object thisValue)
  97. {
  98. if (thisValue != null) return thisValue.ToString().Trim();
  99. return "";
  100. }
  101. #endregion
  102. #region 强转成string 如果失败返回 errorValue
  103. /// <summary>
  104. /// 强转成string 如果失败返回 str
  105. /// </summary>
  106. /// <param name="thisValue"></param>
  107. /// <param name="errorValue"></param>
  108. /// <returns></returns>
  109. public static string TryToString(this object thisValue, string errorValue)
  110. {
  111. if (thisValue != null) return thisValue.ToString().Trim();
  112. return errorValue;
  113. }
  114. #endregion
  115. #region 强转成Decimal 如果失败返回 0
  116. /// <summary>
  117. /// 强转成Decimal 如果失败返回 0
  118. /// </summary>
  119. /// <param name="thisValue"></param>
  120. /// <param name="i"></param>
  121. /// <returns></returns>
  122. public static Decimal TryToDecimal(this object thisValue)
  123. {
  124. Decimal reval = 0;
  125. if (thisValue != null && decimal.TryParse(thisValue.ToString(), out reval))
  126. {
  127. return reval;
  128. }
  129. return 0;
  130. }
  131. #endregion
  132. #region 强转成Decimal 如果失败返回 errorValue
  133. /// <summary>
  134. /// 强转成Decimal 如果失败返回 errorValue
  135. /// </summary>
  136. /// <param name="thisValue"></param>
  137. /// <param name="errorValue"></param>
  138. /// <returns></returns>
  139. public static Decimal TryToDecimal(this object thisValue, int errorValue)
  140. {
  141. Decimal reval = 0;
  142. if (thisValue != null && decimal.TryParse(thisValue.ToString(), out reval))
  143. {
  144. return reval;
  145. }
  146. return errorValue;
  147. }
  148. #endregion
  149. #region 强转成DateTime 如果失败返回 DateTime.MinValue
  150. /// <summary>
  151. /// 强转成DateTime 如果失败返回 DateTime.MinValue
  152. /// </summary>
  153. /// <param name="thisValue"></param>
  154. /// <param name="i"></param>
  155. /// <returns></returns>
  156. public static DateTime TryToDate(this object thisValue)
  157. {
  158. DateTime reval = DateTime.MinValue;
  159. if (thisValue != null && DateTime.TryParse(thisValue.ToString(), out reval))
  160. {
  161. return reval;
  162. }
  163. return reval;
  164. }
  165. #endregion
  166. #region 强转成DateTime 如果失败返回 errorValue
  167. /// <summary>
  168. /// 强转成DateTime 如果失败返回 errorValue
  169. /// </summary>
  170. /// <param name="thisValue"></param>
  171. /// <param name="errorValue"></param>
  172. /// <returns></returns>
  173. public static DateTime TryToDate(this object thisValue, DateTime errorValue)
  174. {
  175. DateTime reval = DateTime.MinValue;
  176. if (thisValue != null && DateTime.TryParse(thisValue.ToString(), out reval))
  177. {
  178. return reval;
  179. }
  180. return errorValue;
  181. }
  182. #endregion
  183.  
  184. #region json转换
  185. /// <summary>
  186. /// 将json序列化为实体
  187. /// </summary>
  188. /// <typeparam name="TEntity"></typeparam>
  189. /// <param name="json"></param>
  190. /// <returns></returns>
  191. public static TEntity JsonToModel<TEntity>(this string json)
  192. {
  193. JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
  194. return jsSerializer.Deserialize<TEntity>(json);
  195. }
  196. /// <summary>
  197. /// 将实体序列化为json
  198. /// </summary>
  199. /// <param name="model"></param>
  200. /// <returns></returns>
  201. public static string ModelToJson<T>(this T model)
  202. {
  203. JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
  204. return jsSerializer.Serialize(model);
  205. }
  206.  
  207. #endregion
  208.  
  209. #region DataTable List
  210. /// <summary>
  211. /// 将集合类转换成DataTable
  212. /// </summary>
  213. /// <param name="list">集合</param>
  214. /// <returns></returns>
  215. public static DataTable ListToDataTable<T>(this List<T> list)
  216. {
  217. DataTable result = new DataTable();
  218. if (list.Count > 0)
  219. {
  220. PropertyInfo[] propertys = typeof(T).GetProperties();
  221. foreach (PropertyInfo pi in propertys)
  222. {
  223. result.Columns.Add(pi.Name, pi.PropertyType);
  224. }
  225.  
  226. for (int i = 0; i < list.Count; i++)
  227. {
  228. ArrayList tempList = new ArrayList();
  229. foreach (PropertyInfo pi in propertys)
  230. {
  231. object obj = pi.GetValue(list[i], null);
  232. if (obj != null && obj != DBNull.Value)
  233. tempList.Add(obj);
  234. }
  235. object[] array = tempList.ToArray();
  236. result.LoadDataRow(array, true);
  237. }
  238. }
  239. return result;
  240. }
  241. /// <summary>
  242. /// 将datatable转为list
  243. /// </summary>
  244. /// <typeparam name="T"></typeparam>
  245. /// <param name="dt"></param>
  246. /// <returns></returns>
  247. public static List<T> DataTableToList<T>(this DataTable dt)
  248. {
  249. var list = new List<T>();
  250. Type t = typeof(T);
  251. var plist = new List<PropertyInfo>(typeof(T).GetProperties());
  252.  
  253. foreach (DataRow item in dt.Rows)
  254. {
  255. T s = System.Activator.CreateInstance<T>();
  256. for (int i = 0; i < dt.Columns.Count; i++)
  257. {
  258. PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
  259. if (info != null)
  260. {
  261. if (!Convert.IsDBNull(item[i]))
  262. {
  263. info.SetValue(s, item[i], null);
  264. }
  265. }
  266. }
  267. list.Add(s);
  268. }
  269. return list;
  270. }
  271. #endregion
  272.  
  273. }
  274. }

  

ASP.NETC#通用扩展函数之TypeParse 类型转换方便多了的更多相关文章

  1. C#ASP.NET 通用扩展函数之 LogicSugar 简单好用

    说明一下性能方面 还可以接受 循环1000次普通Switch是用了0.001秒 ,扩展函数为0.002秒  , 如果是大项目在有负载均衡的情况下完全可以无视掉,小项目也不会计较这点性能了. 注意需要引 ...

  2. C#ASP.NET 通用扩展函数之 IsWhat 简单好用

    好东西都需要人去整理.分类 注意:需要引用命名空间 SyntacticSugar 用法: /***扩展函数名细***/ //[IsInRange] int num = 100; //以前写法 if ( ...

  3. 通用扩展函数之TypeParse

    代码实现: ".TryToInt();//转换为int失败返回0 var int2 = "2x".TryToInt(); );//转换为int失败返回1 ); " ...

  4. ASP.NET通用权限组件思路设计

    开篇 做任何系统都离不开和绕不过权限的控制,尤其是B/S系统工作原理的特殊性使得权限控制起来更为繁琐,所以就在想是否可以利用IIS的工作原理,在IIS处理客户端请求的某个入口或出口通过判断URL来达到 ...

  5. ASP.NET通用权限系统快速开发框架

    系统在线演示地址: http://120.90.2.126:8051 登录账户:system,密码:system### DEMO下载地址: http://download.csdn.net/detai ...

  6. asp.net 通用的连接数据库实例代码

    asp.net中数据库连接代码,有需要的朋友可以参考一下. <%@ Page Language="C#" AutoEventWireup="true" C ...

  7. Asp.Net Unix时间戳和DateTime类型转换

    using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System. ...

  8. asp网站通用后台代码设计

    main2.css: a:link {color: #333333; text-decoration: none}a:visited {color: #000000; text-decoration: ...

  9. ASP.NET通用权限验证组件实现

    沙发(SF)通用权限验证组件 开篇 本篇介绍通用权限验证的实现代码思路,总共分为导入参数.解析XML.根据XML配置进行处理.返回结果. 代码架构图 1.   类介绍 1.SFWebPermissio ...

随机推荐

  1. netsh-winsock-reset;ping的通公网IP和DNS地址和内网网关,就是不能解析域名;

    winXP cmd-------------> netsh winsock reset ============= 相关知识: netsh winsock reset命令含义是重置 Winsoc ...

  2. finished with non-zero exit 添加v7包报错的问题

    错误: 添加 compile 'com.android.support:appcompat-v7:22.2.0'后报错,里面有其它的jar包,但是只要添加这个v7包就报错. Error:Executi ...

  3. 网页内容导出word/excel的js代码

    IE设置: 工具-> Internet选项-> 安全->自定义级别-> 对没有标记安全级别的ActiveX控件进行初始化  设为启用! 1.导出word //指定区域导出到Wo ...

  4. The Truth About .NET Objects And Sharing Them Between AppDomains

    From http://geekswithblogs.net/akraus1/archive/2012/07/25/150301.aspx I have written already some ti ...

  5. Asp.net Core WebApi 全局异常类

    通过全局异常类,所有程序中遇到的错误都会被拦截,并友好的返回结果. 1.自定义一个全局异常处理类中间件 using Microsoft.AspNetCore.Http; using Newtonsof ...

  6. ch2 创建和销毁对象

    ch2 创建和销毁对象              

  7. C#集合 -- Lists,Queues, Stacks 和 Sets

    List<T>和ArrayList Generic的List和非Generic的ArrayList类支持可变化大小的对象数组,它们也是最常见的集合类.ArrayList实现了IList接口 ...

  8. Flink 案例整合

    1.概述 Flink 1.1.0 版本已经在官方发布了,官方博客于 2016-08-08 更新了 Flink 1.1.0 的变动.在这 Flink 版本的发布,添加了 SQL 语法这一特性.这对于业务 ...

  9. 点击弹出 +1放大效果 -- jQuery插件

    20140110更新: <!doctype html> <html> <head> <meta charset="UTF-8"> & ...

  10. Python strange questions list

    sys.setrecursionlimit(1<<64) Line 3: OverflowError: Python int too large to convert to C long ...