1

I'm working around an array, in which i wanna add some of its values. At some points, for this do be done with just one calculation, it will ask for an index outside the array.

Is there a way to say, 'if an index is outside the array, assume the value to be 0' ?

Something a bit like this:

                   try
                   {

                   grid[x,y] = grid[x-1,y] + grid[x-1,y-1];
                   //This is simplified 

                   x++;

                   }

                   catch (IndexOutOfRangeException)
                   {                           
                           grid[x - 1, y - 1] = 0;
                   }
4

1 回答 1

4

Assuming for simplicity that you have an integer array, you may consider extension method like the following:

static class ArrayExtension
{
    static int SafeGetAt(this int[,] a, int i, int j)
    {
        if(i < 0 || i >= a.GetLength(0) || j < 0 || j >= a.GetLength(1))
            return 0;
        return a[i, j];
    }
}

and then access array elements as

grid.SafeGetAt(x, y);

An alternative approach could be to make a wrapper class which accesses the array internally and inplements an indexer. In this case you may keep using [,]-syntax to access elements.


I would not suggest using exceptions, which are quite slow and should be avoided in regular application workflow.

于 2014-08-11T15:27:38.907 回答