2017-06-12 58 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