首页 > 解决方案 > 更新当前对象类中父类的集合

问题描述

假设我有 2 个课程:

class Folder
{
    public  List<File> AssociatedFiles { get; set; }
}

class File
{
    void Update()
    {
        //How to update parent class and add items to the list
        // Something like AssociatedFiles.Add(...); which obviously I can't
    }
}

现在,假设我想打电话:

myFolder.AssociatedFiles.Update();

并更新作为该类myFolder实例的AssociatedFiles 。Folder

这可能是 OOP 的基础知识,但我正在努力掌握它。

标签: c#oop

解决方案


您可能希望向 File 类中的文件夹添加反向引用。

class Folder

{
    public  List<File> AssociatedFiles { get; set; }
}

class File
{
    public Folder ParentFolder {get; set;}
    //create a constructor that takes the folder as a parameter
    public class File(Folder myFolder) {this.ParentFolder = myFolder;}
    void Update()
    {
        this.ParentFolder.AssociatedFiles.Add()
    }
}

现在,当您初始化文件时,您将调用 File(folder) 并将文件夹传递给它,而不是调用 File()。


推荐阅读