递归函数中列表添加数组后所有数组内容一致问题排查
问题:列表中所有数组元素完全一致,不符合随机值输出预期
我原本期望代码能将随机整数数组填充到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[i] = 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 ... (始终为相同值)
问题原因
- 数组是引用类型:每次向
outputList添加的都是同一个数组的引用,后续对数组的修改会同步到列表中所有指向该数组的引用项,最终列表里所有项显示的都是最后一次修改后的数组内容。 - Random实例重复创建:短时间内多次新建
Random实例,会使用相同的系统时钟种子,导致生成的随机数完全一致。
解决办法
要满足“用上一次迭代的数组值进行下一次迭代”的需求,同时解决上述问题,可做以下修改:
- 只创建一个
Random实例,避免重复初始化导致随机数重复; - 向列表添加数组时,添加当前数组的副本,而非原数组引用,这样后续修改原数组不会影响已存入列表的内容。
修改后的代码
List<int[]> outputList = new(); // 只创建一个Random实例 private readonly Random _rand = new(); private static void Main() { Program program = new(); program.StartTest(); } private void StartTest() { int[] inputArray = new int[3]; Test(inputArray, 10); foreach (var arr in outputList) { Console.WriteLine(string.Join(" ", arr)); } Console.ReadLine(); } private void Test(int[] array, int n) { // 添加数组的副本到列表,而非原引用 outputList.Add((int[])array.Clone()); // 修改原数组,用于下一次迭代 for (int i = 0; i < array.Length; i++) { array[i] = _rand.Next(0, 1000); } n--; if (n > 0) Test(array, n); }
说明
- 使用
(int[])array.Clone()创建数组副本,确保列表中每个元素都是独立的数组实例; - 将
Random实例设为类成员,保证每次生成随机数使用同一个种子序列,输出不同的随机值; - 原数组会被持续修改,作为下一次迭代的输入,满足“用上一次迭代的数组值进行下一次迭代”的需求。
内容的提问来源于stack exchange,提问作者OutOfBrainExcepction
相关产品推荐
相关产品推荐

