c# - 如何检查二维数组中的 key 对是否存在?

标签 c# arrays struct multidimensional-array

我有这个二维数组或结构

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/

相关文章:

java - 连接两个 int[]

c - 将内存分配给包含结构的节点

char* 在分配为结构成员时被截断

c# - 创建要在动态对象上运行的方法列表

c# - ASPX : Redirect, 删除 QueryString 但不在浏览器中创建历史记录

c# - 如何返回具有禁止状态 web api 的 ModelState

c# - 使用 Microsoft.Office.Interop.Word 程序集

javascript - 无法通过 AJAX 将多维数组从 JavaScript 发送到 PHP

javascript - 如何按数组值对 javascript 对象进行排序

c - 使用数组作为结构的元素初始化结构数组