c# - 更新当前对象类中父类的集合
问题描述
假设我有 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 的基础知识,但我正在努力掌握它。
解决方案
您可能希望向 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()。
推荐阅读
- dart - 如何增加整个 MaterialApp 的字体大小?
- python - 降低Tensorflow的一对一张量的等级?
- swift - 当我试图获取 geocodeAddressString 它不断抛出这个错误
- spring-cloud-stream - 错误:无法指定多个目的地
- centos - 安装包时不会自动创建用户和用户组
- c# - 尝试在相机位置与停止时相同的情况下加载场景
- java - Jenkins 致命:无法初始化类 com.microsoft.tfs.core.config.persistence.DefaultPersistenceStoreProvider
- azure - Azure Databricks 到事件中心
- sql - 在所有值中查找 `Name` 的第一个字符的计数,然后对其进行排序(PostgreSQL)
- python-3.x - 如何在python3中创建具有连续数字的nxn大小矩阵