如何在我的条目不为空的情况下初始化我的数组?

How do I initialize my array without my entry being null?

我现在正在构建一个小的扫雷程序。我用一个由单元格组成的二维数组来启动这个运动场。当我启动这个数组时,所有条目都是空的。如何正确启动它?

    public Cell[,] _playField;

...

    public void GeneratePlayField(PlayField playField)
    {
        _playField = new Cell[XSize, YSize];
        foreach (Cell cell in playField._playField)
        {
            if (playField._random.NextDouble() <= playField.FillAmount)
            {
                cell.IsMine = true;
            }
        }
    }

...

internal class Cell
{
    public int Neighbors;
    public bool IsMine;

    public Cell(int neighbors, bool isMine)
    {
        Neighbors = neighbors;
        IsMine = isMine;
    }
}

多维数组有点棘手。您可以使用 2 个 for 循环和 GetLength(dimension):

初始化它们
int YSize = 30, XSize = 10;

Cell[,] numbers = new Cell[YSize, XSize];
for (int row = 0; row < numbers.GetLength(0); row++)
    for (int col = 0; row < numbers.GetLength(1); row++)
        numbers[row, col] = new Cell();

通常使用[row,col](而不是[col,row]),因此一行的元素在内存中是连续的。