我正在尝试制作 parent 和 child 的树结构。问题是我只希望能够在子类和父类中分配子类的父类,而不是其他任何地方:
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# 程序员告诉我使用 friends(比如在 C++ 中),但这些并没有在 C# 中实现,我的所有其他解决方案都失败了。
最佳答案
如果您还可以负责实际创建子项和父项(您可以为此提供工厂方法),则可以使用接口(interface)和私有(private)类来实现这一点。
interface IChild
{
// methods and properties for child, including
IParent Parent { get; } // No setter.
}
interface IParent
{
// Methods and properties for parent
}
现在,您创建一个IChild
的私有(private) 实现,它也有一个Parent setter。在您的代码中调用您的私有(private)实现,但只返回 IChild
和 IParent
。
注意 - 私有(private)类是 C# 中的嵌套类。我无法告诉您这些类应该嵌套在哪个类中——这取决于您的项目。如果没有这样合理的地方,您可以创建子/父 DLL 库,并具有实现公共(public)接口(interface)的 internal
子类和父类。
顺便说一下,我不明白为什么您同时拥有 Parent
和 Child
类,尤其不明白为什么 Child 派生自 Parent。如果你有一个 Node
类,你可以有一个带有私有(private) setter 的 Parent
属性,而不用担心它。
关于c# - 有 parent 和 child 的树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764072/