我有一个二维数组

BoardTile tiles[,];


然后在Init(Point size)中设置其大小:

tiles = new BoardTile[size.X, size.Y];


以及如何初始化所有这些元素,因为它不使用默认的BoardTile()构造函数。它只是分配null

foreach(BoardTile t in tiles) t = new BoardTile()

不起作用。当我尝试打电话时

foreach(BoardTile t in tiles) t.anything()


我得到NullReferenceException

最佳答案

您可以尝试嵌套循环:

  for (int i = 0; i < titles.GetLength(0); ++i)
    for (int j = 0; j < titles.GetLength(1); ++j)
      titles[i, j] = new BoardTile();


编辑:如果嵌套循环太复杂且不可读,请尝试从2D一个BoardTile tiles[][];切换到锯齿状数组,即数组-BoardTile tiles[,]-的数组,例如

   // created and initialized jagged array
   BoardTile tiles[][] = Enumerable
     .Range(size.Y)                      // size.Y lines
     .Select(y => Enumerable             // each line is
        .Range(size.X)                   //   size.X items
        .Select(x => new BoardTile())    //   each of them is BoardTile()
        .ToArray())                      //   materialized as array
     .ToArray();                         // all arrays are array of array

10-07 12:03