我正在制作一个函数,该函数使用反射对象和泛型对象(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;
}
我可以修改此函数以在属性是对象时调用自身吗?
答案 0 :(得分:0)
您可以查看Protobuf.net(可以作为Nuget软件包安装)。它基于Google协议缓冲区,非常容易序列化和反序列化对象或复制对象。