在 C# 中调用方法来填充二维数组

Wil*_*Wil 7 c# arrays methods multidimensional-array

我是一个非常新的程序员,一直在努力编写一个可以接受任何 2D 数组并用 1 到 15 之间的随机整数填充它的方法。我相信我成功地正确构建了我的方法,但我似乎看不到然后如何调用我的方法来填充我在 main 中创建的数组。(我会直接将其填入 main 中,但我也在尝试练习方法。)这是我到目前为止的代码。我感谢你们能够给我的任何帮助,谢谢!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Homework2
{
class Program
{
    static void Main(string[] args)
    {
        int[,] myArray = new int[5,6];
    }

    public int[,] FillArray (int i, int j)
    {
        Random rnd = new Random();
        int[,] tempArray = new int[,]{};
        for (i = 0; i < tempArray.GetLength(0); i++)
        {
            for (j = 0; j < tempArray.GetLength(1); j++)
            {
                tempArray[i, j] = rnd.Next(1, 15);
            }
        }
        return tempArray;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Jon*_*eet 7

您的方法不会填充数组 - 它会创建一个新数组。(也根本不清楚这些参数的用途。)

如果您希望它填充现有数组,则应该将作为参数:

public static void FillArray(int[,] array)
{
    Random rnd = new Random();
    for (int i = 0; i < array.GetLength(0); i++)
    {
        for (int j = 0; j < array.GetLength(1); j++)
        {
            array[i, j] = rnd.Next(1, 15);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以通过以下方式调用它Main

FillArray(myArray);
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 我们不需要返回任何内容,因为调用者已经向我们传递了对要填充的数组的引用
  • 我已将该方法设为静态,因为它不需要访问实例的任何Program状态
  • 一般来说,Random“按需”创建一个新实例是一个坏主意。阅读我的文章Random了解更多详情