If语句逻辑和数组

本文关键字:数组 逻辑和 语句 If | 更新日期: 2023-09-27 18:27:28

我有一个方法(在类中),它传递2个整数,然后在设置为2D网格的锯齿状数组中返回该"坐标"处的值。因此,例如,GetXY(5,6)将返回发生在该位置的任何整数值。

在该方法中,我有一个if语句,它检查传递的值是否不低于零或不高于数组的大小,如果值为,则抛出throw new异常。

该代码部分起作用,只是它只检测行的值是否错误,而不检测列的值是否正确。

以下是我的代码(grid是在类构造函数中创建的):

public int GetXY(int row, int column)
        {
            int[] items = grid[column];
            if (row < 0 || column < 0 || row >= grid.Length || column >= items.Length)
            {
                throw new Exception("The passed coordinates are outside the range of the grid. " +
                    "Passed coordinates: " + row.ToString() + "," + column.ToString() + ".");
            }
            return grid[row][column];
          }

当我在10x10网格上执行GetXY(10,9)时,我会得到我的自定义异常消息,除非我执行了GetXY(9,10),否则我会得到:

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun
ds of the array.
   at ProcGen.ProceduralGrid.GetXY(Int32 row, Int32 column) in C:'Users'Lloyd'do
cuments'visual studio 2010'Projects'ProcGen'ProcGen'ProceduralGrid.cs:line 127
   at ProcGen.Program.Main(String[] args) in C:'Users'Lloyd'documents'visual stu
dio 2010'Projects'ProcGen'ProcGen'Program.cs:line 27

为什么它只适用于行?怎么了?

感谢

If语句逻辑和数组

这条线在你到达条件之前抛出界外

int[] items = grid[column];

只需在确保参数安全后将其向下移动:

public int GetXY(int row, int column)
{
    if (row < 0 || column < 0 || row >= grid.Length || column >= grid[row].Length)
    {
       throw new Exception("The passed coordinates are outside the range of the grid. " +
                "Passed coordinates: " + row.ToString() + "," + column.ToString() + ".");
    }
    return grid[row][column];
}