【发布时间】:2015-03-02 01:52:55
【问题描述】:
我正在尝试制作父母和孩子的树状结构。问题是我只希望能够在子类和父类中分配一个孩子的父母,而不是其他地方:
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# 中实现,并且我的所有其他解决方案都失败了。
【问题讨论】:
-
尝试使用受保护的。
-
这有什么帮助?
-
Protected 是我已经尝试过的事情之一,但是我不能在子类中使用父类的其他实例的受保护字段而不是其自身。
标签: c# parent-child friend tree-structure