数组边界外的索引c#

Index outside the bounds of the array c#

我确实遇到了这个错误...请大家帮帮我 这是我的代码

private int getLastRowCount()
{
    return dg.Rows.Count - 1;
}
double[] minAmounts = new double[getLastRowCount()];
double[] maxAmounts = new double[getLastRowCount()];
double[] chrgeValues = new double[getLastRowCount()];
   for (int ctr = 0; (ctr <= getLastRowCount()); ctr++)
   {
        minAmounts[ctr] = Convert.ToDouble(dg[0, ctr].Value);
        maxAmounts[ctr] = Convert.ToDouble(dg[1, ctr].Value);
        chrgeValues[ctr] = Convert.ToDouble(dg[2, ctr].Value);
   }

C# 中的数组是从零开始的,因此循环到 <= 到 getLastRowCount() 会使你超出末尾 1。您还将行数缩短 1(在 getLastRowCount() 中)。您的代码应该是:

private int getLastRowCount()
{
    return dg.Rows.Count;
}

double[] minAmounts = new double[getLastRowCount()];
double[] maxAmounts = new double[getLastRowCount()];
double[] chrgeValues = new double[getLastRowCount()];

for (int ctr = 0; (ctr < getLastRowCount()); ctr++)
{
    //minAmounts[ctr] = Convert.ToDouble(dg[0, ctr].Value);
    //maxAmounts[ctr] = Convert.ToDouble(dg[1, ctr].Value);
    //chrgeValues[ctr] = Convert.ToDouble(dg[2, ctr].Value);

    // it should be [row, col]. This assumes you have at least 3 columns.
    minAmounts[ctr] = Convert.ToDouble(dg[ctr, 0].Value);
    maxAmounts[ctr] = Convert.ToDouble(dg[ctr, 1].Value);
    chrgeValues[ctr] = Convert.ToDouble(dg[ctr, 2].Value);
}

虽然您可能还应该将 getLastRowCount() 的值存储在某处而不是继续调用它。

所有三个数组的容量必须与dg中的行数相同(假设它是一个数据网格)。

对于ctr计数器,rows.Count - 1很好,但是对于定义数组的容量,这会减少1个容量。

关注评论:

private int getLastRowCount()
{
    return dg.Rows.Count - 1; // let's assume this will return 5.
}
// here we declaring 3 arrays of the size 5.
double[] minAmounts = new double[getLastRowCount()];
double[] maxAmounts = new double[getLastRowCount()];
double[] chrgeValues = new double[getLastRowCount()];
// this loop will iterate 6 times: 0,1,2,3,4,5 since getLastRowRount() result to 5.
   for (int ctr = 0; (ctr <= getLastRowCount()); ctr++)
   {
        minAmounts[ctr] = Convert.ToDouble(dg[0, ctr].Value);
        maxAmounts[ctr] = Convert.ToDouble(dg[1, ctr].Value);
        chrgeValues[ctr] = Convert.ToDouble(dg[2, ctr].Value);
   }

因此,解决方案如 Ceisc 所述,更改此行

for (int ctr = 0; (ctr <= getLastRowCount()); ctr++)

成为:

for (int ctr = 0; (ctr < getLastRowCount()); ctr++)