using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization; namespace Com.AppCode.Helper
{
public class ObjectHelper
{
#region Invoking /// <summary>
/// test
/// </summary>
public void test()
{
var obj = new
{
id = ,
name = "张三",
sex = ,
age = };
//转换
var userModel = ConvertObject<user>(obj);
} /// <summary>
/// 用户
/// </summary>
public class user
{
/// <summary>
/// 编号
/// </summary>
public int id { set; get; } /// <summary>
/// 姓名
/// </summary>
public string name { set; get; } /// <summary>
/// 性别
/// </summary>
public int sex { set; get; } /// <summary>
/// 年龄
/// </summary>
public int age { set; get; } }
#endregion #region Method1 /// <summary>
/// 将object对象转换为实体对象
/// </summary>
/// <typeparam name="T">实体对象类名</typeparam>
/// <param name="asObject">object对象</param>
/// <returns></returns>
public T ConvertObject<T>(object asObject) where T : new()
{
//创建实体对象实例
var t = Activator.CreateInstance<T>();
if (asObject != null)
{
Type type = asObject.GetType();
//遍历实体对象属性
foreach (var info in typeof(T).GetProperties())
{
object obj = null;
//取得object对象中此属性的值
var val = type.GetProperty(info.Name)?.GetValue(asObject);
if (val != null)
{
//非泛型
if (!info.PropertyType.IsGenericType)
obj = Convert.ChangeType(val, info.PropertyType);
else//泛型Nullable<>
{
Type genericTypeDefinition = info.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
obj = Convert.ChangeType(val, Nullable.GetUnderlyingType(info.PropertyType));
}
else
{
obj = Convert.ChangeType(val, info.PropertyType);
}
}
info.SetValue(t, obj, null);
}
}
}
return t;
} #endregion #region Method2 /// <summary>
/// 将object对象转换为实体对象
/// </summary>
/// <typeparam name="T">实体对象类名</typeparam>
/// <param name="asObject">object对象</param>
/// <returns></returns>
public static T ConvertObjectByJson<T>(object asObject) where T : new()
{
var serializer = new JavaScriptSerializer();
//将object对象转换为json字符
var json = serializer.Serialize(asObject);
//将json字符转换为实体对象
var t = serializer.Deserialize<T>(json);
return t;
}
#endregion #region Method3
/// <summary>
/// 将object尝试转为指定对象
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static T ConvertObjToModel<T>(object data) where T : new()
{
if (data == null) return new T();
// 定义集合
T result = new T(); // 获得此模型的类型
Type type = typeof(T);
string tempName = ""; // 获得此模型的公共属性
PropertyInfo[] propertys = result.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查object是否包含此列 // 判断此属性是否有Setter
if (!pi.CanWrite) continue; try
{
object value = GetPropertyValue(data, tempName);
if (value != DBNull.Value)
{
Type tempType = pi.PropertyType;
pi.SetValue(result, GetDataByType(value, tempType), null); }
}
catch
{ } } return result;
} /// <summary>
/// 获取一个类指定的属性值
/// </summary>
/// <param name="info">object对象</param>
/// <param name="field">属性名称</param>
/// <returns></returns>
public static object GetPropertyValue(object info, string field)
{
if (info == null) return null;
Type t = info.GetType();
IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
return property.First().GetValue(info, null);
} /// <summary>
/// 将数据转为制定类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data1"></param>
/// <returns></returns>
public static object GetDataByType(object data1, Type itype, params object[] myparams)
{
object result = new object();
try
{
if (itype == typeof(decimal))
{
result = Convert.ToDecimal(data1);
if (myparams.Length > )
{
result = Convert.ToDecimal(Math.Round(Convert.ToDecimal(data1), Convert.ToInt32(myparams[])));
}
}
else if (itype == typeof(double))
{ if (myparams.Length > )
{
result = Convert.ToDouble(Math.Round(Convert.ToDouble(data1), Convert.ToInt32(myparams[])));
}
else
{
result = double.Parse(Convert.ToDecimal(data1).ToString("0.00"));
}
}
else if (itype == typeof(Int32))
{
result = Convert.ToInt32(data1);
}
else if (itype == typeof(DateTime))
{
result = Convert.ToDateTime(data1);
}
else if (itype == typeof(Guid))
{
result = new Guid(data1.ToString());
}
else if (itype == typeof(string))
{
result = data1.ToString();
}
}
catch
{
if (itype == typeof(decimal))
{
result = ;
}
else if (itype == typeof(double))
{
result = ;
}
else if (itype == typeof(Int32))
{
result = ;
}
else if (itype == typeof(DateTime))
{
result = null;
}
else if (itype == typeof(Guid))
{
result = Guid.Empty;
}
else if (itype == typeof(string))
{
result = "";
}
}
return result;
}
#endregion }
}

C#对象转换工具类的更多相关文章

  1. Json与javaBean之间的转换工具类

    /**  * Json与javaBean之间的转换工具类  *  * {@code 现使用json-lib组件实现  *    需要  *     json-lib-2.4-jdk15.jar  * ...

  2. Json转换工具类(基于google的Gson和阿里的fastjson)

    在项目之中我们经常会涉及到字符串和各种对象的转换,为此特地整理了一下常用的转换方法 一.基于com.google.code.gson封装的json转换工具类 1. 在pom.xml文件里面引入gson ...

  3. 时间日期转换工具类,获取当前时间YYYYMMDD24HHMISS、YYYYMMDDHHMISS

    YYYYMMDD24HHMISS:24小时制时间(显示上只是比YYYYMMDDHHMISS中间多了一个24),例:2018102224112440 YYYYMMDDHHMISS:12小时制时间,例20 ...

  4. 对象转换工具 MapStruct 介绍

    前言 在我们日常开发的分层结构的应用程序中,为了各层之间互相解耦,一般都会定义不同的对象用来在不同层之间传递数据,因此,就有了各种 XXXDTO.XXXVO.XXXBO 等基于数据库对象派生出来的对象 ...

  5. 日期转换工具类 CommUtil.java

    package com.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.ut ...

  6. Android Bitmap与DrawAble与byte[]与InputStream之间的转换工具类【转】

    package com.soai.imdemo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; ...

  7. java 二进制数字符串转换工具类

    java 二进制数字符串转换工具类 将二进制转换成八进制 将二进制转换成十进制 将二进制转换成十六进制 将十进制转换成二进制 package com.iteye.injavawetrust.ad; i ...

  8. DensityUtil【尺寸转换工具类(px、dp互相转换)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 用于项目中dp.px.sp之间的转换以及指定缩放值下的转换. 效果图 暂不需要 代码分析 常用的方法是px2dip.dip2px: ...

  9. 【Java】字节数组转换工具类

    import org.apache.commons.lang.ArrayUtils; import java.nio.charset.Charset; /** * 字节数组转换工具类 */ publi ...

随机推荐

  1. ISO/IEC 9899:2011 条款6.3.2——其它操作数

    6.3.2 其它操作数 6.3.2.1 左值,数组,与函数指派符 1.一个左值是潜在地指派一个对象的一个表达式(具有一个对象类型,而不是void):[注:名字“左值”源自于赋值表达式E1 = E2,在 ...

  2. 5G && 物联网

    可打电话的 2G.能够上网的 3G.满足移动互联网用户需求的 4G 相比,逐步可以商用的 5G 在多重性能上更胜一筹,如 高数据率: 低延迟: 更节能: 有效地降低通信成本: 具备更高的系统容量: 更 ...

  3. 阶段5 3.微服务项目【学成在线】_day17 用户认证 Zuul_02-用户认证-认证服务查询数据库-需求分析&搭建环境

    1.2 认证服务查询数据库 1.2.1 需求分析 认证服务根据数据库中的用户信息去校验用户的身份,即校验账号和密码是否匹配. 认证服务不直接连接数据库,而是通过用户中心服务去查询用户中心数据库. 完整 ...

  4. Qt编写自定义控件59-直方动态图

    一.前言 直方动态图类似于音乐播放时候的柱状图展示,顶部提供一个横线条,当柱状上升的时候,该线条类似于帽子的形式冲到顶端,相当于柱状顶上去的感觉,给人一种动态的感觉,听音乐的同时更加赏心悦目,原理比较 ...

  5. Github排名靠前的iOS库

    //iOS第三方开源库的吐槽和备忘 http://blog.ibireme.com/2013/09/23/ios-third-party-libs/#more-41361 //整理了一份Github上 ...

  6. 123457123456---com.threeObj3.BabyShizi02--- 宝宝识字02

    com.threeObj3.BabyShizi02--- 宝宝识字02

  7. (十)会话跟踪技术之Session

    ---部分转自孤傲苍狼博客 一.Session简单介绍 在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占一个session对象(默认情况下).因此 ...

  8. 超详细的RNN代码实现(tensorflow)

    一.学习单步的RNN:RNNCell 如果要学习TensorFlow中的RNN,第一站应该就是去了解“RNNCell”,它是TensorFlow中实现RNN的基本单元,每个RNNCell都有一个cal ...

  9. 【VS2015软件报错】命名空间 system.windows 中不存在类型或命名空间名称 forms (是否缺少程序集引用 )错误

    C#项目: 添加“using System.Windows.Forms;”之后提示“命名空间 system.windows 中不存在类型或命名空间名称 forms (是否缺少程序集引用 )”错误 详细 ...

  10. 波特词干(Porter Streamming)提取算法无代码单纯理解

    最近写东西提到这个算法,要看一下,结果网上都是直接根据代码解释,对于我这种菜鸟在刚开始看一个算法的时候真心不想直接看代码学.奈何都是各种语言的代码,么得办法.先走了一遍,有了大致的了解,翻译成自己的话 ...