【问题标题】:Mapping complex objects with reflection [duplicate]使用反射映射复杂对象
【发布时间】:2019-02-13 07:20:42
【问题描述】:

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

当属性是一个对象时,我可以修改这个函数来调用它自己吗?

【问题讨论】:

  • 您可以发布自己的非工作示例代码,以便我们查看您目前所获得的内容。大多数没有任何代码的问题都会因为“太宽泛”或“关于‘为什么这段代码不起作用’的问题必须包含代码”之类的原因而被关闭。
  • 这个问题没有代码就很模糊。您希望递归地做什么?请添加minimal reproducible example
  • 为什么不使用 AutoMapper?
  • 自动映射器第二次投票
  • 你在问:我可以修改代码来调用自己:你为什么不简单地尝试一下,看看它是否有效?

标签: c# .net reflection types


【解决方案1】:

您可以查看 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

【讨论】:

  • 这个答案的问题在于它只是一个 nuget 包的链接,没有提到它是如何解决问题的
  • 添加了 stackoverflow 的链接。如果您喜欢,我可以提供示例代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 2012-10-16
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多