数组值不变?

时间:2013-03-28 01:40:56

标签: c#

由于某种原因,这不会编辑输入到其中的数组的大小,并且数据不会添加到输入的数组中。

    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");
    }

2 个答案:

答案 0 :(得分:6)

当您将数组传递给此方法时,您可以按值传递它 - 也就是说,您创建一个全新的变量,该变量也指向同一个对象。如果在方法中编辑变量array以指向新数组,则它也不会使另一个变量指向新数组 - 它仍然指向旧数组。因此,当您返回时,您尚未对传入的array进行任何编辑。

要解决此问题,请在方法末尾return array;,并将签名从void更改为int[]。或者您可以out int[] array作为参数,因此您可以通过引用传递并对其进行编辑。

答案 1 :(得分:2)

简单修复将参数声明为out

public static void RandomizeArray(out 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");
}

你可以这样称呼它:

int[] array;

RandomizeArray(out array);

但是,简单地返回数组可能会更好。

public static int[] GenerateRandomizedArray()
{
    int intRead;
    int intReadSeed;
    Random randomNum = new Random();

    Console.WriteLine("How many ints do you want to randomly generated?");
    intRead = Convert.ToInt32(Console.ReadLine());
    var 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");

    return array;
}