列表C#中的数组double更改值 [英] array double change value in list c#
本文介绍了列表C#中的数组double更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我重新计算用于在列表中输入值的变量时,我不明白为什么列表值会更改.
I can't understand why the value of my list changes when I recalculated the variable used to input the value in the list.
看一个例子.
List<double[]> myList = new List<double[]>();
double[] a = new double[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
myList.Add(a); // Ok List[1] = 1 2 3
a[0] = 4; // List[1] = 4 2 3
a[1] = 5; // List[1] = 4 5 3
a[2] = 6; // List[1] = 4 5 6
myList.Add(a); // List[1] = 4 5 6 and List[2] = 4 5 6
有人可以帮助我吗?
推荐答案
The double[]
type is the reference type - What is the difference between a reference type and value type in c#?. So, when you add it into the List twice you actually add the same array twice.
a [0]
将更改相同的数组- List.Add
方法不会创建您提供的值的副本.
a[0]
before myList.Add(a);
and after will change the same array - List.Add
method does not create copy of the value you provide to it.
您应该每次使用新数组或对其进行复制:
You should use new array each time or make a copy of it:
List<double[]> myList = new List<double[]>();
double[] a = new double[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
myList.Add(a); // Ok List[0] = 1 2 3
a = new double[3];
a[0] = 4; // List[0] = 4 2 3
a[1] = 5; // List[0] = 4 5 3
a[2] = 6; // List[0] = 4 5 6
myList.Add(a); // List[0] = 1 2 3 and List[1] = 4 5 6
这篇关于列表C#中的数组double更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文