C#中多维数组的问题

时间:2017-06-12 20:44:58

标签: c#

在代码中你好,我遇到了一个错误,但我找不到解决方案

我尝试过替代方案但没有效果。 (抱歉坏英语)

未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例。

àProgram.Grid..ctor(Int32 rows,Int32 cols,Boolean initialState)    àProgram.Application.Main(String [] args)

“例外

using System;
namespace Program {

class Cell {

    public int id;
    public int row;
    public int col;
    public bool isAccessible;

    public Cell(int row, int col, int id, bool initialState){

        this.id = id;
        this.row = row;
        this.col = col;

        this.isAccessible = initialState;
    }

}

class Grid {

    private Cell[][] grid;      

    public Grid(int rows, int cols, bool initialState){

        for(int row = 0; row < rows; row++){


            grid[row] = new Object[rows][];

            Console.WriteLine(row);

            for (int col = 0; col < cols; col++){

                int id = (row + 1) * rows - (rows - col);
                grid[row][col] = new Cell(row, col, id, initialState);



            }
        }

    }





}

class Application {


    public static void Main(String[] args){

        Grid grid = new Grid(40, 14, false);


        Console.ReadLine();

    }

}

}

1 个答案:

答案 0 :(得分:0)

您必须初始化grid字段:

using System.Linq; 

...

class Grid {  
  private Cell[][] grid; // it's null when not initialized      

  public Grid(int rows, int cols, bool initialState) {
    //DONE: validate arguments of public (and protected) methods
    if (rows < 0)
      throw new ArgumentOutOfRangeException("rows");
    else if (cols < 0)
      throw new ArgumentOutOfRangeException("cols");

    // we want grid be a jagged array: with "rows" lines each of "cols" items  
    grid = Enumerable
      .Range(0, rows)
      .Select(r => new Cell[cols])
      .ToArray(); 

    for(int row = 0; row < rows; row++){
      for (int col = 0; col < cols; col++) {
        int id = (row + 1) * rows - (rows - col);
        grid[row][col] = new Cell(row, col, id, initialState);
      }
    } 
  }
 ....