我有一个二维数组
BoardTile tiles [,];然后在Init(Point size)中设置它的大小:
tiles = new BoardTile [size.X,size.Y];我如何初始化所有这些元素,因为它…
你可以试试 嵌套循环 :
for (int i = 0; i < titles.GetLength(0); ++i) for (int j = 0; j < titles.GetLength(1); ++j) titles[i, j] = new BoardTile();
的 编辑: 强> 如果 嵌套循环 过于复杂且难以理解,请尝试切换到 锯齿状的阵列 即阵列数组 - BoardTile tiles[][]; - 从 2D 一 BoardTile tiles[,] ,例如
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