首页 > 解决方案 > 使用反射映射复杂对象

问题描述

我正在制作一个使用反射和通用对象(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;
    }

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

标签: c#.netreflectiontypes

解决方案


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

Protobuf-Net 作为复制构造函数

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

开始使用 protobuf-net


推荐阅读