在我的代码中,我使用了一个二维多维数组来表示一个网格(并不总是大小相等,例如 10x15 或 21x7)。在阅读了锯齿状数组如何更快并且通常被认为更好之后,我决定将我的二维数组更改为锯齿状数组。
这就是我声明多维数组的方式:
int[,] array = new int[10, 10];
我试图弄清楚如何声明然后初始化相同的东西,但是使用锯齿状数组。
编辑此代码在一个类中,并且在构造函数中我已经有了:
class ProceduralGrid
{
private int[][] grid;
private int _columns;
private int _rows;
public ProceduralGrid(int rows, int columns)
{
_rows = rows; //For getters
_columns = columns;
//Create 2D grid
int x, y;
grid = new int[rows][];
for (x = 0; x < grid.Length; x++)
{
grid[x] = new int[10];
}
}
public int GetXY(int rows, int columns)
{
if (rows >= grid.GetUpperBound(0) + 1)
{
throw new ArgumentException("Passed X value (" + rows.ToString() +
") was greater than grid rows (" + grid.GetUpperBound(0).ToString() + ").");
}
else
{
if (columns >= grid.GetUpperBound(1) + 1)
{
throw new ArgumentException("Passed Y value (" + columns.ToString() +
") was greater than grid columns (" + grid.GetUpperBound(1).ToString() + ").");
}
else
{
return grid[rows][columns];
}
}
}
}
在另一种方法中,我只是在做:
Console.WriteLine(grid.GetXY(5, 5).ToString());
我收到的错误消息:
Unhandled Exception: System.IndexOutOfRangeException: Array does not have that m
any dimensions.
at System.Array.GetUpperBound(Int32 dimension)
at ProcGen.ProceduralGrid.GetXY(Int32 rows, Int32 columns) in C:\Users\Lloyd\
documents\visual studio 2010\Projects\ProcGen\ProcGen\ProceduralGrid.cs:line 115
at ProcGen.Program.Main(String[] args) in C:\Users\Lloyd\documents\visual stu
dio 2010\Projects\ProcGen\ProcGen\Program.cs:line 27
我做错了什么,我应该怎么做?