我正在尝试制作父母和孩子的树形结构。问题是我只希望能够在child和parent类中指派孩子的父母,而在其他地方:
public class Parent
{
public static Parent Root = new Parent();
private List<Child> children = new List<Child>();
public ReadOnlyCollection<Child> Children
{
get { return children.AsReadOnly(); }
}
public void AppendChild(Child child)
{
child.Parent.RemoveChild(child);
child.children.Add(child);
child.Parent = this; //I need to asign the childs parent in some way
}
public void RemoveChild(Child child)
{
if (this.children.Remove(child))
{
child.Parent = Parent.Root; //here also
}
}
}
public class Child : Parent
{
private Parent parent = Parent.Root;
public Parent Parent
{
get { return this.parent; }
private set { this.parent = value; } //nothing may change the parent except for the Child and Parent classes
}
}
一位非C#程序员告诉我使用朋友(例如在C ++中),但是这些朋友不是在C#中实现的,因此我所有其他解决方案都失败了。
最佳答案
这可能无法回答您的问题,但这是另一种选择。这是一个节点结构,您可以使用如下形式:
public class Node
{
private Node _parent;
private List<Node> _children = new List<Node>();
public Node(Node parent)
{
_parent = parent
}
public ReadOnlyCollection<Node> Children
{
get { return _children.AsReadOnly(); }
}
public void AppendChild(Node child)
{
// your code
}
public void RemoveChild(Node child)
{
// your code
}
}
我看到@zmbq刚刚编辑过以建议类似的内容。
关于c# - parent 与子女的树形结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27764072/