C# 检查元素索引是否在2d数组中(用于在任何方向上移动一个)

C# 检查元素索引是否在2d数组中(用于在任何方向上移动一个),c#,arrays,unity3d,C#,Arrays,Unity3d,我有一个二维的物体阵列 private Cell[,] mapCells = new Cell[10, 10]; 我想检查我的数组中是否存在坐标为x=m和y=n的键值对 我喜欢这个 bool cellExists = index.x >= 0 && // check left index.y >= 0 && // check bottom index.x < mapCell

我有一个二维的物体阵列

private Cell[,] mapCells = new Cell[10, 10];
我想检查我的数组中是否存在坐标为x=my=n的键值对

我喜欢这个

        bool cellExists = index.x >= 0 && // check left
              index.y >= 0 && // check bottom
              index.x < mapCells.GetLength(0) && // check right
              index.y < mapCells.GetLength(1); // check top
所以我知道方向是什么


当我向右移动时,我想我不需要检查左侧。

不,没有其他方法来测试这一点。我能想到的唯一优化是缓存大小,但您在这方面收获不多

那么,您可以将其隐藏在扩展方法后面,使其看起来更优雅

public static class Extensions
{
    public static bool IsExist(this Cell[,] mapCells, Cell index)
    {
        bool cellExists = index.x >= 0 &&
               index.y >= 0 &&
               index.x < mapCells.GetLength(0) &&
               index.y < mapCells.GetLength(1);

        return cellExists;
    }
}

这取决于你所说的“优雅”是什么意思。你可以这样做(在我的头顶上):

其思想是首先获得x或y的绝对值,然后检查最小值和轴上限值是否会产生x或y。如果有,你就很好


它较短,但可读性值得怀疑。我怀疑它是否比您最初的解决方案快。

我认为,这很好。您如何定义更优雅?“这是相当基于意见的,不是吗?”希姆布罗姆比尔:我认为他的意思是更短或更快。我认为在这两个方面都没有太多的可能性。我编辑了我的问题,也许新的信息会有所帮助。我投票将这个问题作为离题结束,因为这是一个要求改进工作代码的评论,因此应该转到。我编辑了我的问题,也许新的信息会有所帮助
public static class Extensions
{
    public static bool IsExist(this Cell[,] mapCells, Cell index)
    {
        bool cellExists = index.x >= 0 &&
               index.y >= 0 &&
               index.x < mapCells.GetLength(0) &&
               index.y < mapCells.GetLength(1);

        return cellExists;
    }
}
mapCells.IsExist(index);
bool cellExists = Math.Min(mapCells.GetLength(0) - 1, Math.Abs(x)) == x 
                && Math.Min(mapCells.GetLength(1) - 1, Math.Abs(y)) == y