[英]array double change value in list c#
I can't understand why the value of my list changes when I recalculated the variable used to input the value in the list. 当我重新计算用于在列表中输入值的变量时,我不明白为什么列表的值会更改。
Look's an example. 看一个例子。
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
Can someone help me? 有人能帮我吗?
The double[]
type is the reference type - What is the difference between a reference type and value type in c#? double[]
类型是引用类型-c#中的引用类型和值类型有什么区别? . 。 So, when you add it into the List twice you actually add the same array twice.
因此,当您两次将其添加到列表中时,实际上两次添加了相同的数组。
a[0]
before myList.Add(a);
myList.Add(a);
之前的a[0]
myList.Add(a);
and after will change the same array - List.Add
method does not create copy of the value you provide to it. 之后将更改相同的数组
List.Add
方法不会创建您提供给它的值的副本。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.