代码之家  ›  专栏  ›  技术社区  ›  scharette

更新当前对象类中父类的集合

  •  -1
  • scharette  · 技术社区  · 6 年前

    假设我有两个班:

    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 它是 Folder 类。

    这可能是OOP的基础,但我正在尝试掌握它的窍门。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Harshita Gupta    6 年前

    您需要添加对文件类内文件夹的后向引用。

    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()。