【发布时间】:2015-01-28 06:41:44
【问题描述】:
我的程序中有 3 维数组。我想调试其中的值,然后将此数组放入另一个数组中,我想在其中找到差异。
我试过这个:
Weights weights = new Weights(); // init inside
List<Weights> weightsDebug = new List<Weigts>();
weightsDebug.Add(weights); // I'd put first weigths into the list
for(int i = 0; i < 100; i++) {
// do some bad things with weights;
weightsDebug.Add(weights);
}
在那之后,我在 weigthsDebug 的所有 99 个元素中得到了相同的权重值。我尝试调试并意识到,weigts 数组正在更改。我知道问题出在引用中(通过链接复制,而不是通过值复制)——所有推送到 weightsDebug 的数组元素都与主循环中的 weights 链接。
我用谷歌搜索了一下,发现了一些如何复制一维数组的方法。接下来我尝试了:
我在 Weights 类中添加了 Clone 方法:
double[][][] values;
public Weights Clone() {
Weights clone = new Weights();
clone.values = (double[][][]) this.values.Clone();
return clone;
}
public Weights()
{
Console.WriteLine("Constructor WITHOUT arguments fired");
}
现在我在复制权重时这样做:
Weights weights = new Weights(); // init inside
List<Weights> weightsDebug = new List<Weigts>();
weightsDebug.Add(weights); // I'd put first weigths into the list
for(int i = 0; i < 100; i++) {
// do some bad things with weights;
Weights weightsClone = weights.Clone();
weightsDebug.Add(weightsClone);
}
我仍然在整个调试数组中获得最后更改的值。我该如何纠正它?
【问题讨论】:
标签: c# arrays multidimensional-array clone deep-copy