[英]How to add an array to a list by value not by reference?
Is there a way to add an array to a list of arrays by value and not by reference?有没有办法按值而不是按引用将数组添加到数组列表中?
Example: The following prints out "6, 7, 8, 9, 10".示例:以下打印出“6, 7, 8, 9, 10”。 I want it to write out "1, 2, 3, 4, 5".
我希望它写出“1、2、3、4、5”。
int[] testArray = new int[5] { 1, 2, 3, 4, 5 };
List<int[]> testList = new List<int[]>();
testList.Add(testArray);
testArray[0] = 6;
testArray[1] = 7;
testArray[2] = 8;
testArray[3] = 9;
testArray[4] = 10;
foreach(int[] array in testList)
{
Console.WriteLine("{0}, {1}, {2}, {3}, {4}", array[0], array[1], array[2], array[3], array[4]);
}
制作一个副本:
testList.Add(testArray.ToArray());
您必须Clone()
数组,即创建数组的浅拷贝并将其添加到列表中。
testList.Add((int[])testArray.Clone());
Instead of代替
testList.Add(testArray);
use用
testList.Add(testArray.Clone() as int[]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.