C#、ASP.NET通用扩展工具类之TypeParse

所属分类: 软件编程 / C#教程 阅读数: 85
收藏 0 赞 0 分享

用法:

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
 
  }
}

更多精彩内容其他人还在看

c#开发word批量转pdf源码分享

已经安装有Office环境,借助一些简单的代码即可实现批量Word转PDF,看下面的实例源码吧
收藏 0 赞 0 分享

c# xml API操作的小例子

这篇文章主要介绍了c# xml API操作的小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

c#唯一值渲染实例代码

这篇文章主要介绍了c#唯一值渲染实例代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

淘宝IP地址库采集器c#代码

这篇文章主要介绍了淘宝IP地址库采集器c#代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C#在后台运行操作(BackgroundWorker用法)示例分享

BackgroundWorker类允许在单独的专用线程上运行操作。如果需要能进行响应的用户界面,而且面临与这类操作相关的长时间延迟,则可以使用BackgroundWorker类方便地解决问题,下面看示例
收藏 0 赞 0 分享

c#文本加密程序代码示例

这是一个加密软件,但只限于文本加密,加了窗口控件的滑动效果,详细看下面的代码
收藏 0 赞 0 分享

c#生成站点地图(SiteMapPath)文件示例程序

这篇文章主要介绍了c#生成站点地图(SiteMapPath)文件的示例,大家参考使用
收藏 0 赞 0 分享

C# 键盘Enter键取代Tab键实现代码

这篇文章主要介绍了C# 键盘Enter键取代Tab键实现代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

C# WinForm导出Excel方法介绍

在.NET应用中,导出Excel是很常见的需求,导出Excel报表大致有以下三种方式:Office PIA,文件流和NPOI开源库,本文只介绍前两种方式
收藏 0 赞 0 分享

C#串口通信程序实例详解

在.NET平台下创建C#串口通信程序,.NET 2.0提供了串口通信的功能,其命名空间是System.IO.Ports,创建C#串口通信程序的具体实现是如何的呢?让我们开始吧
收藏 0 赞 0 分享
查看更多