C# 将object对象转换为实体对象
C# 将object对象转换为实体对象.一共两种方法.
第一种方法,通过反射遍历的方式转换。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /// <summary> /// 将object对象转换为实体对象 /// </summary> /// <typeparam name="T">实体对象类名</typeparam> /// <param name="asObject">object对象</param> /// <returns></returns> private 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; } |
第二种方法
需引用:
程序集:Newtonsoft.Json.dll
命名空间:Newtonsoft.Json
代码如下:
/// <summary> /// 将object对象转换为实体对象 /// </summary> /// <typeparam name="T">实体对象类</typeparam> /// <param name="asObject">object对象</param> /// <returns></returns> public static T ConvertObject<T>(object asObject) where T : new() { //此方法将object对象转换为json字符 var json = Newtonsoft.Json.JsonConvert.SerializeObject(asObject); //再将json字符转换为实体对象 var t = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); return t; }
调用方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /// <summary> /// test /// </summary> public void test() { var obj = new { id=1,name= "张三" ,sex=1,age=22 }; //转换 user 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 ; } } |
是不是很简单?
更多内容可访问:http://pythonjishu.com/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】