【发布时间】:2023-02-13 20:22:15
【问题描述】:
我希望下面的代码用一些随机整数数组填充“outputList”列表。 事实证明它没有。当我在控制台上输出列表时,“outputList”列表中的每个数组都有相同的数字。
任何想法为什么这个列表充满了相同的数组?
随机值只是为了表明输出始终相同。我知道有一些更好的方法可以用随机值填充列表。
代码:
List<int[]> outputList = new();
private static void Main()
{
Program program = new();
program.StartTest(); //start non-static StartTest()-method
}
private void StartTest()
{
int[] inputArray = new int[3]; //create array {0, 0, 0}
Test(inputArray, 10); //call Test()-method, repeat 10 times
for(int i = 0; i < outputList.Count; i++) //finally print the "outputList"
{
string outputStr = string.Join(" ", outputList[i]);
Console.WriteLine(outputStr);
}
Console.ReadLine();
}
private void Test(int[] array, int n)
{
outputList.Add(array); //add the array to the outputList
//fill array with random integers
Random rand = new();
for(int i = 0; i < array.Length; i++)
array[rand.Next(0, array.Length)] = rand.Next(0, 1000);
//call function again, if n > 0
n--;
if (n > 0)
Test(array, n);
}
预期产出
23 432 437
43 645 902
342 548 132
...(随机值)
实际产量
252 612 761
252 612 761
252 612 761
...(总是相同的值)
我是 stackoverflow 的新手,所以请原谅我可能犯的任何低级错误。
【问题讨论】:
-
您总是将相同的数组添加到列表中。因此,通过列表中的所有引用可以看到对数组的更改。您需要在该点创建数组的副本。您对
Test的递归调用可能应该复制一份。 -
大概只是完全删除给
Test方法的数组并在Test中创建一个新数组。测试不使用给定的数组的包含。
标签: c#