c# - 使用反射映射复杂对象
问题描述
我正在制作一个使用反射和通用对象(T)映射两个不同对象(具有等效属性和类型)的函数。我的函数适用于具有简单属性(如 int 或字符串类型)的对象,但现在我必须添加对对象属性或对象列表的支持。我可以递归地执行此操作还是不可行?由于工作原因,我无法发布代码。活动代码如下:
public static T MapObjects<T>(object sourceObject) where T : new()
{
T destObject = new T();
Type sourceType = sourceObject.GetType();
Type targetType = destObject.GetType();
foreach (PropertyInfo p in sourceType.GetProperties())
{
PropertyInfo targetObj = targetType.GetProperty(p.Name);
if (targetObj == null)
continue;
targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
}
return destObject;
}
当属性是对象时,我可以修改此函数以调用自身吗?
解决方案
您可以查看 Protobuf.net(可以作为 Nuget 包安装)。它基于 Google 协议缓冲区,并且相当容易序列化和反序列化对象或复制对象。
推荐阅读
- jquery - 带有输入时间和播放暂停选项的 Jquery 倒数计时器
- javascript - WebUSB 按 deviceClass 和 deviceSubClass 过滤
- gcc - 为什么 armv7l-unknown-linux-gnueabihf-objdump 在运行时会给出“无效的 bfd 目标”?
- python - 列表理解和扁平化深度数据结构
- angular - TypeError:无法读取未定义的属性“播放器”
- javascript - 滚动时如何保持两个元素之间的固定距离
- tsql - 在同一列上使用两个不同的 sum() 的问题
- c - 左值需要作为赋值的左操作数 - 错误
- ios - 如何获取 iPhone 中保存的所有帐户信息?
- pytorch - 致命错误 LNK1181:无法打开输入文件 'Project\pytorch\build\lib\caffe2_protos.lib'