如何检查二维数组中的密钥对是否存在?

New*_*ger 1 c# arrays struct multidimensional-array

我有这个二维数组或结构

public struct MapCell
{
    public string tile;
}

public MapCell[,] worldMap;
Run Code Online (Sandbox Code Playgroud)

但是无法检查此数组中是否存在密钥对……没有可用的方法。

我试图这样做

if (worldMap[tileX, tileY] != null) {
}
Run Code Online (Sandbox Code Playgroud)

它不起作用:

Error 1 Operator '!=' cannot be applied to operands of type 'Warudo.MapCell' and '<null>'
Run Code Online (Sandbox Code Playgroud)

和为

if (worldMap[tileX, tileY].tile != null) {
Run Code Online (Sandbox Code Playgroud)

它也不起作用(当碰到不存在的元素时会弹出异常)。

Index was outside the bounds of the array.
Run Code Online (Sandbox Code Playgroud)

那么,如何检查密钥对是否存在?

Chr*_*lsh 5

您从未提到要得到哪个错误-数组超出范围或空引用。如果您超出了数组的范围,则应在进行空检查之前加上类似...的内容。

// make sure we're not referencing cells out of bounds of the array
if (tileX < arr.GetLength(0) && tileY < arr.GetLength(1))
{
    // logic
}
Run Code Online (Sandbox Code Playgroud)

当然,最好只存储最大数组边界,而不是每次都获取它们的长度。

对于使用类而不是结构的建议,我也第二(第三?)的建议。

编辑:您是否真的初始化过该字段?您尚未将其包含在代码示例中。例如worldMap = new MapCell[100,100];,然后填充数组...