我有这个二维数组或结构
public struct MapCell
{
public string tile;
}
public MapCell[,] worldMap;
但是没有办法检查这个数组中是否存在 key 对......没有可用的方法。
我试着这样做
if (worldMap[tileX, tileY] != null) {
}
它不起作用:
Error 1 Operator '!=' cannot be applied to operands of type 'Warudo.MapCell' and '<null>'
并为
if (worldMap[tileX, tileY].tile != null) {
它也不起作用(当它遇到不存在的元素时会弹出异常)。
Index was outside the bounds of the array.
那么,如何检查 key 对是否存在?
最佳答案
你从来没有提到你得到了哪个错误——数组越界或空引用。如果你让数组越界,你应该在你的空检查之前用一些类似的东西......
// make sure we're not referencing cells out of bounds of the array
if (tileX < arr.GetLength(0) && tileY < arr.GetLength(1))
{
// logic
}
当然,最好只存储最大数组边界,而不是每次都获取它们的长度。
我也是第二(第三?)使用类而不是结构的建议。
编辑:你有没有真正初始化过这个字段?您尚未将其包含在代码示例中。例如
worldMap = new MapCell[100,100];
,然后填充数组...
关于c# - 如何检查二维数组中的 key 对是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6256764/