用反射映射复杂的对象

时间:2018-09-08 00:22:38

标签: c# .net reflection types

我正在制作一个函数,该函数使用反射对象和泛型对象(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;
    }

我可以修改此函数以在属性是对象时调用自身吗?

1 个答案:

答案 0 :(得分:0)

您可以查看Protobuf.net(可以作为Nuget软件包安装)。它基于Google协议缓冲区,非常容易序列化和反序列化对象或复制对象。

Protobuf-Net as copy constructor

https://www.c-sharpcorner.com/article/serialization-and-deserialization-ib-c-sharp-using-protobuf-dll/

Getting started with protobuf-net

相关问题