我不明白为什么我会在下面的代码中遇到超出范围的异常。 _maxRowIndex
和 _maxColIndex
的值分别为 5
和 0
。当 row
和 col
都等于 0
时,第一次抛出异常。我不明白为什么 0, 0
会超出数组范围。
_cells = new ToolBarButton[_maxRowIndex, _maxColIndex];
.
.
.
for (int col = 0; col <= _maxColIndex; col++) {
for (int row = 0; row <= _maxRowIndex; row++)
{
if (_cells[row, col] == null)
{
PopulateCell(toolBarbutton, row, col);
}
}
}
最佳答案
数组索引从 0 开始,一直到 [upperbound-1]。由于您的循环从 0 开始,因此它必须以 < 极限值而不是 <= 极限值结束。因此,将循环中的“<=”更改为“<”。例如:
col <= _maxColIndex
应该改为
col < _maxColIndex
关于c# - 尝试访问数组元素时出现 IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4252579/