C#对象转换工具类
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#对象转换工具类的更多相关文章
- Json与javaBean之间的转换工具类
/** * Json与javaBean之间的转换工具类 * * {@code 现使用json-lib组件实现 * 需要 * json-lib-2.4-jdk15.jar * ...
- Json转换工具类(基于google的Gson和阿里的fastjson)
在项目之中我们经常会涉及到字符串和各种对象的转换,为此特地整理了一下常用的转换方法 一.基于com.google.code.gson封装的json转换工具类 1. 在pom.xml文件里面引入gson ...
- 时间日期转换工具类,获取当前时间YYYYMMDD24HHMISS、YYYYMMDDHHMISS
YYYYMMDD24HHMISS:24小时制时间(显示上只是比YYYYMMDDHHMISS中间多了一个24),例:2018102224112440 YYYYMMDDHHMISS:12小时制时间,例20 ...
- 对象转换工具 MapStruct 介绍
前言 在我们日常开发的分层结构的应用程序中,为了各层之间互相解耦,一般都会定义不同的对象用来在不同层之间传递数据,因此,就有了各种 XXXDTO.XXXVO.XXXBO 等基于数据库对象派生出来的对象 ...
- 日期转换工具类 CommUtil.java
package com.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.ut ...
- Android Bitmap与DrawAble与byte[]与InputStream之间的转换工具类【转】
package com.soai.imdemo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; ...
- java 二进制数字符串转换工具类
java 二进制数字符串转换工具类 将二进制转换成八进制 将二进制转换成十进制 将二进制转换成十六进制 将十进制转换成二进制 package com.iteye.injavawetrust.ad; i ...
- DensityUtil【尺寸转换工具类(px、dp互相转换)】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 用于项目中dp.px.sp之间的转换以及指定缩放值下的转换. 效果图 暂不需要 代码分析 常用的方法是px2dip.dip2px: ...
- 【Java】字节数组转换工具类
import org.apache.commons.lang.ArrayUtils; import java.nio.charset.Charset; /** * 字节数组转换工具类 */ publi ...
随机推荐
- 最简陋的python数据
python 爬虫 最简陋的第一次爬取写入CSV文件(只是想纪念一下,以后看看现在自己多年轻) github
- 计算机基础——Java笔记一
电子管-晶体管 摩尔定律 18个月变一次 贝尔实验室 C语言是基础.芯片领域软件领域 机器语言 ——汇编语言——高级语言 (面向过程,面向对象) 基本的逻辑怎么用代码实 ...
- oracle 编译无效对象
在数据库中,会存在一些无效的对象,导致这种现象的发生原因很多,其中最常见的就是数据库升级(例如修改了表的结构),迁移而引起. 编译无效对象的方式: 1 使用alter **** compile 语句进 ...
- React拾遗(下)
reconciliation(协调算法) react用于更新DOM的算法.基于两点假设,实现了一个启发的O(n)算法: 两个不同类型的元素将产生不同的树. 通过渲染器附带key属性,开发者可以示意哪些 ...
- jar启动脚本shell
#!/bin/bash#这里可替换为你自己的执行程序,其他代码无需更改 APP_NAME=/opt/server/msp/health-api/health-2.0.2.jar#使用说明,用来提示输入 ...
- Faster RCNN论文学习
Faster R-CNN在Fast R-CNN的基础上的改进就是不再使用选择性搜索方法来提取框,效率慢,而是使用RPN网络来取代选择性搜索方法,不仅提高了速度,精确度也更高了 Faster R-CNN ...
- Qt编写控件属性设计器2-拖曳控件
一.前言 上一篇文章把插件加载好了,并且把插件中的所有控件都显示到了列表框中,这次要做的就是实现拖曳控件的功能,用户选择一个控件拖曳到画布上,松开,在松开位置处自动实例化该控件,这个需要用到dropE ...
- curl 的用法指南
简介 curl 是常用的命令行工具,用来请求 Web 服务器.它的名字就是客户端(client)的 URL 工具的意思. 它的功能非常强大,命令行参数多达几十种.如果熟练的话,完全可以取代 Postm ...
- iOS-模态视图动画
ios视图切换的动画效果 方法1.把下面的这段代码加到viewController或者view出现的时候就OK self.view.transform=CGAffineTransformMakeSca ...
- 35个高级Python知识点总结
原文地址:https://blog.51cto.com/xvjunjie/2156525 No.1 一切皆对象 众所周知,Java中强调“一切皆对象”,但是Python中的面向对象比Java更加彻底, ...