我正在尝试制作父母和孩子的树状结构。问题是我只想能够在子类和父类中分配孩子的父母,而不是其他地方:
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# 中实现,并且我的所有其他解决方案都失败了。