出于某种原因,这不会编辑输入到其中的数组的大小,并且不会将数据添加到输入的数组中。
public static void RandomizeArray(int[] array)
{
int intRead;
int intReadSeed;
Random randomNum = new Random();
Console.WriteLine("How many ints do you want to randomly generated?");
intRead = Convert.ToInt32(Console.ReadLine());
array = new int[intRead];
Console.WriteLine("What's the maximum value of the randomly generated ints?");
intReadSeed = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < intRead; i++)
{
array[i] = (randomNum.Next(intReadSeed));
}
Console.WriteLine("Randomization Complete.\n");
}
最佳答案
当你将数组传递给这个方法时,你是按值传递它——也就是说,你创建了一个全新的变量,它也指向同一个对象。如果您在方法中编辑变量 array
以指向一个新数组,它不会同时使另一个变量指向您的新数组——它仍然指向旧数组。因此,当您返回时,您还没有对传入的 array
进行任何编辑。
要解决此问题,请在方法末尾return array;
,并将签名从void
更改为int[]
。或者您可以将 out int[] array
作为参数,这样您就可以通过引用传递并对其进行编辑。
关于c# - 数组值没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15672761/