更新基类的值,以便所有派生类也被更新

问题描述

我希望减少正在工作的内存需求,并遇到一些派生类的问题。目前,我有4个派生类,它们继承了相同的基类并重写了相同的方法,但是对于每个派生类,重写方法中的功能都不同。这有助于清理大量代码,并使很多维护工作更加轻松。但是,每个派生类都有一个.zshrc全局变量,该变量变得非常大。这是设置类的方法

long[,] File_Vals

与此有关,必须更新4套 public class BaseClass { public long[,] File_Vals; public int Max_rows; internal void DoWork(){} } public class FirstDerivedClass : BaseClass { public DerivedClass(long[,] file_values,int max_rows) { File_Vals = file_values; Max_rows = max_rows } internal new void DoWork() { // does work stuff } } public class SecondDerivedClass : BaseClass ... public class Testing { FirstDerivedClass firstDerived; SecondDerivedClass secondDerived; ThirdDerivedClass thirdDerived; FourthDerivedClass fourthDerived; public void Setup(long[,int max_rows) { firstDerived = new FirstDerivedClass(file_values,max_rows); secondDerived = new SecondDerivedClass(file_values,max_rows); thirdDerived = new ThirdDerivedClass(file_values,max_rows); fourthDerived = new FourthDerivedClass(file_values,max_rows); } ... public void DoStuff(long[,int max_rows) { // updated versions of file_values and max_rows. } } 。有没有一种方法只需更新父/基类,从而更新其他派生/子类?还是有一种方法,每个派生类/子类都没有自己的File_values对象版本,并且只有一个它们都可以访问?现在File_values对象中可以有1200万行,甚至更多,因此需要考虑内存使用情况。

解决方法

与此相关,必须更新4组File_values

否,问题中的代码中只有一个共享的long[,]实例(因为数组是reference types)和4个引用。您可以使用以下代码轻松检查它:

Setup(new long[1,1],1);
Console.WriteLine(object.ReferenceEquals(firstDerived.File_Vals,secondDerived.File_Vals)); // prints True 

因此,基本上,您有32*464*4位的“开销”取决于平台。

您可以将File_Vals字段设为readonly,以防止为其分配其他值(引用),或者更好的是,仅获取属性。