c# - 有 parent 和 child 的树结构

标签 c# parent-child friend tree-structure

我正在尝试制作 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)实现,但只返回 IChildIParent

注意 - 私有(private)类是 C# 中的嵌套类。我无法告诉您这些类应该嵌套在哪个类中——这取决于您的项目。如果没有这样合理的地方,您可以创建子/父 DLL 库,并具有实现公共(public)接口(interface)的 internal 子类和父类。

顺便说一下,我不明白为什么您同时拥有 ParentChild 类,尤其不明白为什么 Child 派生自 Parent。如果你有一个 Node 类,你可以有一个带有私有(private) setter 的 Parent 属性,而不用担心它。

关于c# - 有 parent 和 child 的树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764072/

相关文章:

c# - 有没有办法保护类变量不被函数外修改

c++ - 我对友元函数的理解

c++ - 不能将一个类的方法定义为另一个类的友元

c# - 在 Emgu 或 opencv 中组合多个图像

c# - window.location.href 上的第二个参数在 Controller 上获取 NULL

c# - 当远程 SQL Server 数据库的 scaffold-DbContext 时,构建失败

javascript - 从父背景颜色和透明父背景颜色中读取边框颜色值

C - 终止的好方法

c# - ShouldSerialize*() 与 *指定的条件序列化模式

c# - 在 C# 中反序列化 XML 时如何获取对父对象的引用?