2017-06-12 45 views
-2

向你问好多维数组的问题,我遇到了一个错误,我没有找到解决办法与代码中的C#

我试过的替代品,但没有奏效。 (对不起)(英语)

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

àProgram.Grid..ctor(的Int32行的Int32 COLS,布尔初始化状态) àProgram.Application.Main(字串[] 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(); 

    } 

} 

} 

回答

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); 
     } 
    } 
    } 
.... 
+0

非常感谢您的帮助,我明白了 – ken