索引是数组的外部边界

时间:2014-03-07 18:32:39

标签: c#

当我运行它时,它表示索引超出了数组的范围,但事实并非如此。 如果我改变公共静态ConectorRec [] ch = new ConectorRec [74]; to ConectorRec [] ch = new ConectorRec [75];那么它们并不是都引用了一个对象,而是在我的代码的其他部分抛出了其他错误。

using System;
using System.Drawing;
using System.Windows;
using System.Windows.Forms;
using System.Collections.Generic;

namespace Dots
{
    public static class Conectors
    {
        public static ConectorRec[] ch = new ConectorRec[74];
        public static void intitialize()
        {
            ch[0] = new ConectorRec(new Rectangle(10, 20, 10, 40));
            ch[1] = new ConectorRec(new Rectangle(20, 10, 40, 10));
            ch[2] = new ConectorRec(new Rectangle(20, 60, 40, 10));
            ch[3] = new ConectorRec(new Rectangle(60, 20, 10, 40));
            int t = 0;
            int tt = 1;
            for (int i = 4; i<73; i++)
            {
                t++;
                if (t == 1)
                {
                    ch[i] = new ConectorRec(new Rectangle(50 * tt + 20, 10, 40, 10));
                }
                if (t == 2)
                {
                    ch[i] = new ConectorRec(new Rectangle(50 * tt + 20, 60, 40, 10));
                }
                if (t == 3)
                {
                    tt++;
                    ch[i] = new ConectorRec(new Rectangle(50 * tt + 10, 20, 10, 40));
                    t = 0;
                }
            }
            ch[74] = new ConectorRec(new Rectangle(10, 70, 10, 40));
        }
    }
}

请告诉我我做错了什么以及如何解决这个错误。

3 个答案:

答案 0 :(得分:8)

  

当我运行它时,它表示索引超出了数组的范围,但它不是

是的。即使我无法确定问题,我总是打赌运行时比开发人员对此的看法更准确......

这是循环后的问题:

ch[74] = new ConnectorRec(...);

你已经声明数组在这里有74个元素:

public static ConectorRec[] ch = new ConectorRec[74];

因此有效索引为0..73(含)。如果要使74成为有效索引,则需要将其声明为 75 元素:

public static ConectorRec[] ch = new ConectorRec[75];

答案 1 :(得分:4)

数组索引从零开始。您的数组大小为74,因此您的最后一个元素是ch[73]而不是74。您可以使用GetUpperBound方法验证这一点:

var maxIndex = ch.GetUpperBound(0); // this will return 73

来自C#规范Section 12. Arrays

  

维度的长度决定了该维度的有效索引范围:对于长度 N 的维度,索引的范围可以从0到 N - 1(含)

在这种情况下,您的数组长度(N)为74,因此最大值。 index是73(N -1)。

答案 2 :(得分:1)

错误是由

引起的
ch[74] = new ConectorRec(new Rectangle(10, 70, 10, 40));

您的数组大小为74,这意味着您的最大索引为73,因为数组索引从0开始

相关问题