【问题标题】:IndexOutOfRangeException on multidimensional array despite using GetLength check尽管使用 GetLength 检查,但多维数组上的 IndexOutOfRangeException
【发布时间】: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


【解决方案1】:

我怀疑是0 超出了范围。

Excel 数组是从 1 开始的,而不是您可能期望的从 0 开始的。

【讨论】:

  • 你说得对。没有更多的例外!我没有读取正确的数据,我怀疑是因为我的 LINQ 语句中有错误。我会尝试验证这是一个单独的问题,只要是这样,我就会回来接受这个。很棒的收获!
猜你喜欢
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多