数组方法调试问题

时间:2010-12-21 16:23:59

标签: c# .net

我正在使用方法填充数组但是我收到同一问题的2个错误 当尝试使用该方法分配孔数组时以及在方法中返回填充的数组时!

我在有问题的行

上添加了明确的错误评论
static void Main(string[] args)
{
uint n = uint.Parse(Console.ReadLine());
uint m = uint.Parse(Console.ReadLine());
int[,] array=new int [n,m];
array=FillArrayMethodC(n,m); //Cannot implicitly convert type 'int' to 'int[*,*]'

}

static int FillArrayMethodC(uint n, uint m)
{
  int[,] a=new int [n,m];

  //fill the array

  return a; //Cannot implicitly convert type 'int[*,*]' to 'int'
}

如何以正确的方式返回整个数组并分配它!!!

感谢您的帮助 BR

3 个答案:

答案 0 :(得分:3)

更改FillArrayMethod的返回类型。

static int[,] FillArrayMethodC(uint n, uint m)

答案 1 :(得分:1)

目前还不清楚是否要在Main或fill方法中创建新数组。看起来你可能真的想要这个:

static void Main(string[] args)
{
    uint n = uint.Parse(Console.ReadLine());
    uint m = uint.Parse(Console.ReadLine());
    int[,] array=new int [n,m];
    FillArrayMethodC(array, n, m); // pass array into "fill" method
}

static void FillArrayMethodC(int[,] a, uint n, uint m)
{
    //fill the array
    ...
    // nothing to return
}

这里发生的是您的Main函数正在创建数组并将其传递给fill方法。 fill方法不会创建数组,因此不会返回任何内容。

答案 2 :(得分:1)

您无需在FillArrayMethodC()方法中创建数组,因为您已经创建了它。如果该方法只是填充数组并且需要知道数组维度,则可以将数组传递给方法并获取该方法内的维度。我怀疑你想要这样的东西:

    static void Main(string[] args)
    {
        uint n = uint.Parse(Console.ReadLine());
        uint m = uint.Parse(Console.ReadLine());
        int[,] array = new int[n, m];
        FillArrayMethodC(array); 

    }

    static void FillArrayMethodC(int[,] arr)
    {

        int numRows = arr.GetLength(0);
        int numCols = arr.GetLength(1);

        for (int i = 0; i < numRows; i++)
            for (int j = 0; j < numCols; j++)
            {
                // Fill your array here, e.g.:
                arr[i, j] = i * j;
            }

        return; 
    }