繁体   English   中英

如何按值而不是引用将数组添加到列表中?

[英]How to add an array to a list by value not by reference?

有没有办法按值而不是按引用将数组添加到数组列表中?

示例:以下打印出“6, 7, 8, 9, 10”。 我希望它写出“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());

代替

testList.Add(testArray);

testList.Add(testArray.Clone() as int[]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM