我想拥有一个二维游戏板,每个字段都是一个自定义类,其中包含有关此字段的信息以及属性。游戏板的大小在实例化时是已知的,而属性的值则未知。实例化之后,我想为每个字段随机设置它们。我最初的想法是创建一个数组,而不是一个列表,因为游戏板的大小始终是固定的。
public class GameBoard
{
private int _xValue;
private int _yValue;
private int _bombs;
private int _fields;
public Field[][] gameBoard;
public GameBoard(int x, int y)
{
_xValue = x;
_yValue = y;
_fields = _xValue * _yValue;
gameBoard = new[] { new Field[_xValue], new Field[_yValue] };
//Here I have to initialize every Field
for (int i = 0; i < _xValue; i++)
{
for (int j = 0; j < _yValue; j++)
{
//Set properties of Field
//For example: gameBoard[i][j].IsBomb = RandomBoolean;
//Here I get NullReferenceExceptions
}
}
}
}
我确实理解为什么这不起作用。我尝试了列表,二维数组或类似的锯齿数组,这是我想要的。如何以一种可读,干净的方式解决此问题?
编辑
字段类:
public class Field
{
public bool IsBomb { get; set; }
public bool IsFlagged { get; set; }
}
我试图在嵌套的forloop中添加gameBoard[i][j] = new Field();
。这导致IndexOutOfRangeException。
在使用它之前,您必须初始化每个游戏板数组索引的索引。
意思是,您必须先完成.IsBomb = true
才能设置index = new Field();
public GameBoard(int x, int y)
{
_xValue = x;
_yValue = y;
_fields = _xValue * _yValue;
gameBoard = new[] { new Field[_xValue], new Field[_yValue] };
//Here I have to initialize every Field
for (int i = 0; i < _xValue; i++)
{
for (int j = 0; j < _yValue; j++)
{
//Set properties of Field
gameBoard[i][j] = new Field();
gameBoard[i][j].IsBomb = true;
//Here I get NullReferenceExceptions
}
}
}
所以