欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-21 09:46:59
用法: var int1 = "2".trytoint();//转换为int失败返回0 var int2 = "2x".trytoint(); var int...

用法:

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