用法:

            var int1 = "2".TryToInt();//转换为int失败返回0
var int2 = "2x".TryToInt();
var int3 = "2".TryToInt(1);//转换为int失败返回1
var int4 = "2x".TryToInt(1); var d1 = "2".TryToMoney(); //同上
var d2 = "2x".TryToMoney();
var d3 = "2".TryToMoney(1);
var d4 = "2x".TryToMoney(1); string a = null;
var s1 = a.TryToString();
var s3 = a.TryToString("1"); var d11 = "2".TryToDecimal();
var d22 = "2x".TryToDecimal();
var d33 = "2".TryToDecimal(1);
var d44 = "2x".TryToDecimal(1); var de1 = "2013-1-1".TryToDate();
var de2 = "x2013-1-1".TryToDate();
var de3 = "x2013-1-1".TryToDate(DateTime.Now); //json和model转换
var json = new { id = 1 }.ModelToJson();
var model = "{id:1}".JsonToModel<ModelTest>(); //list和dataTable转换
var dt = new List<ModelTest>().ListToDataTable();
var list = dt.DataTableToList<ModelTest>();

  

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Data;
using System.Reflection;
using System.Collections; namespace SyntacticSugar
{
/// <summary>
/// ** 描述:类型转换
/// ** 创始时间:2015-6-2
/// ** 修改时间:-
/// ** 作者:sunkaixuan
/// ** 使用说明:
/// </summary>
public static class TypeParseExtenions
{
#region 强转成int 如果失败返回 0
/// <summary>
/// 强转成int 如果失败返回 0
/// </summary>
/// <param name="thisValue"></param>
/// <param name="i"></param>
/// <returns></returns>
public static int TryToInt(this object thisValue)
{
int reval = 0;
if (thisValue != null && int.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
#endregion
#region 强转成int 如果失败返回 errorValue
/// <summary>
/// 强转成int 如果失败返回 errorValue
/// </summary>
/// <param name="thisValue"></param>
/// <param name="i"></param>
/// <returns></returns>
public static int TryToInt(this object thisValue, int errorValue)
{
int reval = 0;
if (thisValue != null && int.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
#endregion
#region 强转成double 如果失败返回 0
/// <summary>
/// 强转成money 如果失败返回 0
/// </summary>
/// <param name="thisValue"></param>
/// <param name="i"></param>
/// <returns></returns>
public static double TryToMoney(this object thisValue)
{
double reval = 0;
if (thisValue != null && double.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return 0;
}
#endregion
#region 强转成double 如果失败返回 errorValue
/// <summary>
/// 强转成double 如果失败返回 errorValue
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
public static double TryToMoney(this object thisValue, int errorValue)
{
double reval = 0;
if (thisValue != null && double.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
#endregion
#region 强转成string 如果失败返回 ""
/// <summary>
/// 强转成string 如果失败返回 ""
/// </summary>
/// <param name="thisValue"></param>
/// <param name="i"></param>
/// <returns></returns>
public static string TryToString(this object thisValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return "";
}
#endregion
#region 强转成string 如果失败返回 errorValue
/// <summary>
/// 强转成string 如果失败返回 str
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
public static string TryToString(this object thisValue, string errorValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return errorValue;
}
#endregion
#region 强转成Decimal 如果失败返回 0
/// <summary>
/// 强转成Decimal 如果失败返回 0
/// </summary>
/// <param name="thisValue"></param>
/// <param name="i"></param>
/// <returns></returns>
public static Decimal TryToDecimal(this object thisValue)
{
Decimal reval = 0;
if (thisValue != null && decimal.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return 0;
}
#endregion
#region 强转成Decimal 如果失败返回 errorValue
/// <summary>
/// 强转成Decimal 如果失败返回 errorValue
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
public static Decimal TryToDecimal(this object thisValue, int errorValue)
{
Decimal reval = 0;
if (thisValue != null && decimal.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
#endregion
#region 强转成DateTime 如果失败返回 DateTime.MinValue
/// <summary>
/// 强转成DateTime 如果失败返回 DateTime.MinValue
/// </summary>
/// <param name="thisValue"></param>
/// <param name="i"></param>
/// <returns></returns>
public static DateTime TryToDate(this object thisValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && DateTime.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
#endregion
#region 强转成DateTime 如果失败返回 errorValue
/// <summary>
/// 强转成DateTime 如果失败返回 errorValue
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
public static DateTime TryToDate(this object thisValue, DateTime errorValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && DateTime.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
#endregion #region json转换
/// <summary>
/// 将json序列化为实体
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static TEntity JsonToModel<TEntity>(this string json)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
return jsSerializer.Deserialize<TEntity>(json);
}
/// <summary>
/// 将实体序列化为json
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static string ModelToJson<T>(this T model)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
return jsSerializer.Serialize(model);
} #endregion #region DataTable List
/// <summary>
/// 将集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(this List<T> list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = typeof(T).GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
} for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
if (obj != null && obj != DBNull.Value)
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
/// <summary>
/// 将datatable转为list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> DataTableToList<T>(this DataTable dt)
{
var list = new List<T>();
Type t = typeof(T);
var plist = new List<PropertyInfo>(typeof(T).GetProperties()); foreach (DataRow item in dt.Rows)
{
T s = System.Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
if (info != null)
{
if (!Convert.IsDBNull(item[i]))
{
info.SetValue(s, item[i], null);
}
}
}
list.Add(s);
}
return list;
}
#endregion }
}

  

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. Swift - 计算文本高度

    Swift - 计算文本高度 效果 源码 // // String+StringHeight.swift // StringHeight // // Created by YouXianMing on ...

  2. 实施vertex compression所遇到的各种问题和解决办法

    关于顶点压缩,好处是可以减少带宽,一定程度提高加载速度,可以提高约5-10%的fps,特别是mobile上,简单描述就是: 压缩之前(32字节) position float3 12normal fl ...

  3. ADB工具包15秒快速安装器,已集合ADB、FASTBOOT工具箱和最新的驱动程序

    http://www.cnroms.com/adb-and-fastboot-toolkit-with-google-usb-drivers.html 通过电脑管理安卓手机需要的三个最常用的工具包集合 ...

  4. nodejs配置简单HTTP服务器

    1.介绍 http-server 是一个简单的零配置命令行HTTP服务器, 基于 nodeJs. 如果你不想重复的写 nodeJs 的 web-server.js, 则可以使用这个. 2.安装 npm ...

  5. android:style.xml

    <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2006 The Andr ...

  6. Codeforces Round #182 (Div. 1)题解【ABCD】

    Codeforces Round #182 (Div. 1)题解 A题:Yaroslav and Sequence1 题意: 给你\(2*n+1\)个元素,你每次可以进行无数种操作,每次操作必须选择其 ...

  7. Excel 二级下拉菜单

    http://jingyan.baidu.com/article/cd4c2979f31967756f6e6066.html http://hi.baidu.com/chenshake/item/e1 ...

  8. win10 Enable developer Mode

    经过漫长的安装过程 win10终于装上了vs2015 rc-   写个小程序试试 结果提示:   根据提示打开 设置--更新--for developer 据说应该有这么个界面:   但是这个界面根本 ...

  9. ECshop鼠标划过弹出 微信扫一扫代码

     效果如上图 安装步骤:1,将以下代码放到page_header.lbi里   <div class="f_l"><a href="../index.p ...

  10. android 监听软键盘的收起与打开

    参考: http://toughcoder.net/blog/2015/10/09/android-trick-detect-soft-keyboard-show-slash-hide/ packag ...