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

最新文章

  1. hibernate学习一(hibernate简介与准备)
  2. 工欲善其事必先利其器——web调试工具firebug
  3. Single Number II
  4. JavaScript基础——数据类型
  5. FTP\TFTP
  6. As Easy As Possible
  7. cat-mvc 一个nodejs mvc 框架
  8. new Random().nextInt
  9. 常用JS模板
  10. opencv在arm和x86在移植
  11. All about Performing User-Managed Database Recovery
  12. C语言对齐
  13. 应届生求职:IT博客真能当技术型职位的求职利器?
  14. Python 包管理(PYPA)
  15. vue+nginx编译部署
  16. 微信小程序实现显示和隐藏控件-头像-取值-bindblur事件
  17. 阿里云物联网平台体验(NetGadgeteer+C#篇)
  18. Docker搭建wordpress博客环境(Centos7)
  19. TSPL学习笔记(1)
  20. c#除掉字符串最后一个字符几种方法

热门文章

  1. perl 语法速查 | 模块安装
  2. php Class 'ZipArchive' not found怎么解决?
  3. 如果前面的IO操作出问题了,按照我们代码的意思,不就try catch 了吗,这样的话线程就没关闭了,就会造成线程泄露。 那怎么解决这个问题呢,其实也简单,把关闭线程的方法写到finally里就可以了。
  4. C#-片段-插入片段:测试
  5. web端安全测试工具
  6. OpenStack Magnum项目简介
  7. Maven 打war包
  8. (一)Asp.net web api中的坑-【找不到与请求 URI匹配的 HTTP 资源】
  9. list自定义排序工具类
  10. 在C/C++中常用的符号