我正在创建一个包含子实例列表的类,我需要记住它们的父对象。
class Node
{
List<Node> childNodes;
Node ParentNode;
public Node(List<Node> nodes)
{
childNodes = nodes;
foreach (var node in childNodes)
{
node.ParentNode = this;
}
}
}
这是一个好方法还是我错过了什么?
答案 0 :(得分:0)
I'm assuming this isn't a chicken egg problem. The Parent would be created first and therefore children would be added later.
public class Node
{
public List<Node> ChildNodes {get; private set;}
public Node ParentNode {get; private set;}
public Node():this(null)
{
}
public Node(Node parentNode)
{
ParentNode = parentNode;
ChildNodes = new List<Node>();
}
public void AddChildNode(Node childNode){
childNode.ParentNode = this;
ChildNodes.Add(childNode);
}
}