I have a class Cell:
public class Cell
{
public enum cellState
{
WATER,
SCAN,
SHIPUNIT,
SHOT,
HIT
}
public Cell()
{
currentCell = cellState.WATER;
MessageBox.Show(currentCell.ToString());
}
public cellState currentCell { get; set; }
}
我随后尝试在以下类中使用它:
public class NietzscheBattleshipsGameModel
{
private byte MAXCOL = 10;
private byte MAXROW = 10;
public Cell[,] HomeArray;
private Cell[,] AwayArray;
public NietzscheBattleshipsGameModel()
{
HomeArray = new Cell [MAXCOL, MAXROW];
AwayArray = new Cell [MAXCOL, MAXROW];
}
public string alphaCoords(Int32 x)
{
if (x < 0 || x > 9)
{
throw new ArgumentOutOfRangeException();
}
char alphaChar = (char)('A' + x);
return alphaChar.ToString();
}
public void test()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
// Object reference not set to an instance of an object.
MessageBox.Show(HomeArray[i,j].currentCell.ToString());
///////////////////////////////////////////////////////
}
}
}
}
在上面的代码中,我遇到了对象引用未设置为对象实例(在/////之间)。
我尝试创建一个单一的Cell实例,它可以正常工作。
public struct Cell
而不是一个class
,那么在这些循环中你就不必逐个使用new()
来初始化它们,因为struct
是值类型,因此总是使用其成员的默认值进行初始化。 - herzmeister