【问题标题】:.Net Merge two identical objects, all properties, recursively when null.Net合并两个相同的对象,所有属性,当为null时递归
【发布时间】:2018-12-10 21:34:59
【问题描述】:

我有一个任务,我提供了一个基础对象,其中包含来自我们数据服务的对象和原语,并将其与客户端提供的相同对象上提供的数据耦合。它最终需要成为一个完整的对象。我将对象称为“MyObject”。

以下是数据服务中对象的外观:

MyObject.FirstName = null
MyObject.LastName = null
MyObject.DataProperty1 = anotherobject
   anotherobject.property1 = somevalue1
   anotherobject.property2 = somevalue2
   anotherobject.property2 = somevalue2
MyObject.DataProperty2 = yetanotherobject
   yetanotherobject.property1 = someothervalue1
   yetanotherobject.property2 = someothervalue2
   yetanotherobject.property3 = someothervalue3
   yetanotherobject.property4 = someothervalue4

这是客户端提供的对象的样子

MyObject.FirstName = John
MyObject.LastName = Doe
MyObject.DataProperty1 = anotherobject
   anotherobject.property1 = null
   anotherobject.property2 = null
   anotherobject.property2 = null
MyObject.DataProperty2 = yetanotherobject
   yetanotherobject.property1 = null
   yetanotherobject.property2 = null
   yetanotherobject.property3 = null
   yetanotherobject.property4 = null

我不能指望确切知道哪些子项对象将为空或不为空,但我知道递归地,我需要最终合并的对象包含来自两个原始对象的实际数据,而不是空值。显然,这些对象会比我上面输入的要复杂得多,但我的问题的要点是有效的。

我尝试过类似merging two objects in C# 之类的操作,但无法找出非原语。

我真的不认为这是 AutoMapper 的任务,因为 MyObject 的类型对于客户端和数据端都是同一个类。将其映射到自身是没有意义的。

太糟糕了,我不能去 MyObject1 + MyObject2 = NewCombinedObject 哈哈。

另外,这是遗留代码,我意识到它根本不是“最佳实践”。不过还是需要解决问题。

【问题讨论】:

    标签: c# .net object merge


    【解决方案1】:

    我可以看到您会遇到两个潜在的阻碍因素:嵌套对象引用引用其父级的子级。两者都可能导致无限递归场景和内存不足错误。

    您可以通过简单地决定不合并任何比 x 级别深的深度来缓解嵌套问题。这并不理想,但它可以防止该场景的无限递归。

    孩子提到父母的问题更为复杂。您必须能够将合并的对象映射到它们的原始对象,然后在您的输出中,将引用节点映射回您已经合并的节点。这不是胆小的人的任务。

    这是 AutoMapper 无法为您完成的任务吗?如果是这样,我的直觉告诉我,它会比你重新发明它更好地为你做这件事,并且大大降低了出错的风险。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多