【发布时间】: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 哈哈。
另外,这是遗留代码,我意识到它根本不是“最佳实践”。不过还是需要解决问题。
【问题讨论】: