如果是语句逻辑和数组

时间:2013-08-13 18:31:10

标签: c#

我有一个方法(在一个类中),它传递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];
          }

当我执行GetXY(10,9)(10x10)网格时,我收到自定义异常消息,除非我执行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

为什么它只适用于行?出了什么问题?

由于

1 个答案:

答案 0 :(得分:10)

这条线在你到达条件

之前抛出界限
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];
}
相关问题