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 ...
随机推荐
- OpenResty之replace-filter-nginx-module
原文: openresty/replace-filter-nginx-module 1. 概要 location /t { default_type text/html; echo abc; repl ...
- Linux fdisk命令创建逻辑分区
[root@localhost ~]# fdisk /dev/sdb …省略部分输出… Command (m for help): n #建立新分区 Command action l logical ...
- easyUI的datagrid表格的使用
实现easyUI表格的里面数据的增删改查功能.SQL使用Oracle和mybatis. 话不多说,直接上代码. 首先是前段部分的. var session = GetSession(); var pa ...
- 如何用Deepin-wine安装运行win32的程序
创建容器 容器就是win32程序运行的环境,可以理解为一个极小的windows,在Linux下面实际对应一个文件目录,如QQ对应的容器目录是~/.deepinwine/Deepin-QQ. 创建容器最 ...
- docker pull 失败: server misbehaving
在docker pull 镜像时一直报错: Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp: lo ...
- chrome浏览器备忘
记录日常使用Chrome遇到的问题. audio控件播放音频问题 打开http://www.cdfive.com,发现音乐没有自动播放,F12打开控制台发现有如下报错: Uncaught (in pr ...
- OpenJudge计算概论-年龄与疾病
/*========================================================== 年龄与疾病 总时间限制: 1000ms 内存限制: 65536kB 描述 某医 ...
- NTC热敏电阻基础以及应用和选择(转)
源:NTC热敏电阻基础以及应用和选择 NTC被称为负温度系数热敏电阻,是由Mn-Co-Ni的氧化物充分混合后烧结而成的陶瓷材料制备而来,它在实现小型化的同时,还具有电阻值-温度特性波动小.对各种温度变 ...
- CardView 简介和使用
CardView 简介 本文链接:https://blog.csdn.net/ShawnXiaFei/article/details/81568537CardView 是 Google 官方发布 MD ...
- Ionic 的安装运行
1.学习前准备工作 1.必须得安装 nodejs (建议安装最新的稳定版本) 2.必须有 Angular 基础:https://www.loaderman.com/goods-1047.html 2. ...