【发布时间】:2015-05-19 13:44:08
【问题描述】:
我正在使用以下代码从 Excel 电子表格中读取值:
// Start with passed
int lastPassRow = sheets[passedVehicles].GetLength(0);
for (int i = 1; i < lastPassRow; i++)
{
// Exception here
if(DateTime.TryParse(sheets[passedVehicles][i, 0].ToString(), out result))
{
passedDates.Add((DateTime)sheets[passedVehicles][i, 0]);
}
}
sheets[passedVehicles] 的类型是 Object[,] 的多维数组,上面的 for 循环在 i = 1 时给了我一个 IndexOutOfRange 异常,尽管我检查了行数。
我为有问题的电子表格添加了一些日志记录,并已验证:
- i = 1 是失败的迭代
-
lastPassRow的值为4 -
sheets[passedVehicles].GetLength(1)的值也是四。
在我看来,所有值都在范围内。还有其他可能导致此异常的原因吗?
注意:我从 i = 1 开始,因为第 0 行是电子表格中的标题,不包含我要读取的数据。
【问题讨论】:
-
不应该是
sheets[passedVehicles][0, i]吗? -
@Kryptos 不,我一直使用
[row, column]约定,它适用于除此之外的所有内容。 -
如果您评估
sheets[passedVehicles].GetLowerBound(0)和1相同,会怎样? Excel 数组是从 1 开始的,而不是从 0 开始的,因此它的下限可能是1而不是0。 C# 数组始终从 0 开始,但更通用的Array类实际上允许任意上下限。 -
好的,然后试试
sheets[passedVehicles][i, 1]
标签: c# multidimensional-array indexoutofrangeexception