【发布时间】:2014-05-18 21:52:46
【问题描述】:
有没有办法通过值而不是通过引用将数组添加到数组列表中?
示例:以下打印出“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]);
}
【问题讨论】:
-
您需要创建数组的副本。
-
所有内容都按值添加到列表中。您的困惑源于数组与所有对象一样不是 C# 中的值。
testArray不是一个对象——它是一个引用(指向一个对象的指针)。
标签: c# arrays list pass-by-value