2013-08-21 250 views
1

我想創建一個二維數組對象(基本上是一個XY座標系),但我不知道如何。我有一個創建Tile對象的Map類。在Map類的構造函數中,我編寫了代碼來創建Tile對象的2D鋸齒狀數組。C#無法創建對象數組

我不知道爲什麼這不起作用,以前我創建了2D鋸齒狀整數數組,並且工作正常。我想如何創建對象數組?

這是我得到的錯誤:

Unhandled Exception: System.NullReferenceException: Object reference not set to 
an instance of an object. 
    at ObjectArray.Map..ctor(Int32 NumberOfRows, Int32 NumberOfColumns) in C:\Use 
rs\Lloyd\documents\visual studio 2010\Projects\ObjectArray\ObjectArray\Map.cs:li 
ne 27 
    at ObjectArray.Program.Main(String[] args) in C:\Users\Lloyd\documents\visual 
studio 2010\Projects\ObjectArray\ObjectArray\Program.cs:line 18 

我Tile.cs

class Tile 
{ 
    public int TileID { get; set; } 

} 

而且我Map.cs:

class Map 
{ 
    private Tile[][] TileGrid; 

    public int Columns { get; private set; } 
    public int Rows { get; private set; } 

    public Map(int NumberOfRows, int NumberOfColumns) 
    { 
     Rows = NumberOfRows; 
     Columns = NumberOfColumns; 


     TileGrid = new Tile[NumberOfRows][]; 
     for (int x = 0; x < TileGrid.Length; x++) 
     { 
      TileGrid[x] = new Tile[NumberOfColumns]; 
     } 

     //Test for the right value. 
     TileGrid[0][0].TileID = 5; 
     Console.WriteLine(TileGrid[0][0].TileID); 

    } 
} 

回答

5

此行

TileGrid[x] = new Tile[NumberOfColumns]; 

創建給定長度的null引用的數組。所以,你需要遍歷並初始化對象每個參考:

TileGrid = new Tile[NumberOfRows][]; 
for (int x = 0; x < TileGrid.Length; x++) 
{ 
    TileGrid[x] = new Tile[NumberOfColumns]; 
    for (int y = 0; y < TileGrid[x].Length; y++) 
    { 
     TileGrid[x][y] = new Tile(); 
    } 
} 
0

之前,你可以使用一個元素,你必須做出一個新的......這樣的:

TileGrid[0][0] = new Tile(); 

然後你就可以使用它:

TileGrid[0][0].TileID = 5; 

錯誤消息是正確的,你試圖引用一個空的瓷磚位置。