微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c#-检查元素索引是否在2d数组内(用于向任意方向移动一个)

我有这个二维数组的对象

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 < mapCells.GetLength(0) && // check right
              index.y < mapCells.GetLength(1); // check top

因此,使用此布尔值,我检查单元格是在地图上还是在外部.

有没有更优雅的方法来检查这一点?

编辑:

当检查这个时,我得到一个运动方向像

  Vector2 dir = new Vector2(/* this can be
     (0,1) // up
     (0,-1) // down
     (-1,0) // left
     (1,0) // right
  */);

所以我知道给出哪个方向.

当我向右移动时,我认为不需要检查左侧.

解决方法:

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

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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐