1

I have a method (in a class) which is passed 2 integers and then returns the value at that "coordinate" in a jagged array that is setup as a 2D grid. So, for example, GetXY(5,6) would return whatever integer value happens to be at that position.

In the method I have an if statement that checks that the passed values are not below zero or higher than the size of the array, and throws an exception with throw new if the values are.

The code is partly working, except that it only detects when the row is at a wrong value, and does nothing when the column is at a wrong value.

Here is my code (grid is created in the class constructor):

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];
          }

When I do GetXY(10,9) (on a 10x10) grid, I get my custom exception message, except if I do GetXY(9, 10) I get:

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

Why does it only work for rows? What's going wrong?

Thanks

4

1 回答 1

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];
}
于 2013-08-13T18:32:44.897 回答