我们已经盯着这个问题很久了,浪费了宝贵的时间。
我们有这些对象,我们称它们为组件。我们的应用程序允许您基于现有组件 创建一个新组件。
父级的所有值都是“继承的”(阅读:可通过 component.Parent
属性访问)除非您覆盖了一个值——例如你想给它一个新名称,但保留其余的父值。
// Exiting parent-child object chain
BaseObject {Id = 1, Name = "Base", Description = "Base description", Notes = "Awesome object", ParentId = null}
ChildObject1 {Id = 2, Name = "", Description = "", Notes = "", ParentId = 1}
ChildObject2 {Id = 3, Name = "Custom Name", Description = "", Notes = "", ParentId = 2}
ChildObject3 {Id = 4, Name = "", Description = "Final object", Notes = "", ParentId = 3}
现在我想从上到下将其展平,对子项上的任何空值使用父项的现有值。
// End result after flattening/merging
ChildObject3 {Id = 4, Name = "Custom Name", Description = "Final object", Notes = "Awesome object", ParentId = 3}
注意:没有子属性,只有子知道父。 parent 不知道 child 。
如何在不使用丑陋的while(child.Parent != null)
构造和创建previousComponent
、currentComponent
等对象的情况下解决这个问题跟踪设定值。
最佳答案
递归 DeepCopy
方法怎么样,比如:
public class ComponentClass()
{
public ComponentClass DeepCopy(ComponentClass comp)
{
CopyAllNonEmptyPropertiesTo(comp);
if (comp.StillHasEmptyProperties())
return Parent.DeepCopy(comp);
else
return comp;
}
}
关于c# - 展平父/子对象链,沿途合并值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26506121/