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

巧了我就是萌 提交于 2019-12-23 07:00:26

问题


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". I want it to write out "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]);
}

回答1:


Make a copy:

testList.Add(testArray.ToArray());



回答2:


You have to Clone() the array i.e. create shallow copy of array and add that in the list.

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



回答3:


Instead of

testList.Add(testArray);

use

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


来源:https://stackoverflow.com/questions/22899129/how-to-add-an-array-to-a-list-by-value-not-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!