【问题标题】:Calling a method to fill a 2d array in C#在 C# 中调用方法来填充二维数组
【发布时间】:2015-12-13 14:57:41
【问题描述】:

我是一个非常新的程序员,并且一直在努力编写一种可以采用任何二维数组并用 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;
    }
}

}

【问题讨论】:

    标签: c# arrays multidimensional-array methods


    【解决方案1】:

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

    如果你想让它填充一个现有的数组,你应该有 that 作为参数:

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

    然后你可以通过Main 调用它:

    FillArray(myArray);
    

    注意事项:

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

    【讨论】:

    • 我认为第二个for 应该使用array,而不是tempArray
    • @DaveZych - 你敢质疑无所不知的 Jon Skeet 吗? :)
    • @Tim 没有人能免于犯错 :)
    • @DaveZych - 是的,我知道。只是无法抗拒评论,因为这是 Jon Skeet(TM) 的回答:)
    • 谢谢乔恩!我也很欣赏所有有用的见解。刚开始写你发给我的文章!
    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 2015-07-19
    • 2014-12-23
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多