将所有子对象链接到当前的适当方法是什么?

时间:2012-10-24 04:04:44

标签: c# parent-child

我正在创建一个包含子实例列表的类,我需要记住它们的父对象。

class Node
{
    List<Node> childNodes;
    Node ParentNode;
    public Node(List<Node> nodes)
    {
        childNodes = nodes;
        foreach (var node in childNodes)
        {
            node.ParentNode = this;
        }
    }
}

这是一个好方法还是我错过了什么?

1 个答案:

答案 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);
    }

}