簡體   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