【问题标题】:C# Array Index ErrorC# 数组索引错误
【发布时间】:2014-03-30 00:19:48
【问题描述】:

我要添加的简单数组,但是我不断收到此索引超出范围错误。环顾四周,无法弄清楚我哪里出错了,我假设这与我使用 pos 变量的位置有关。发布任何我认为可能相关的内容。提前致谢。

const int MAX = 5;
    Account[] db = new Account[MAX];

    // global variable for position in array
    int pos;

    private void Form1_Load(object sender, EventArgs e)
    {
        // initialise the array with instantiated objects
        for (int i = 0; i < MAX; i++)
            db[i] = new Account();
    }

private void OpenAcc_Click(object sender, EventArgs e)
    {
        //hide menu
        hide_menu();

        //make new form elements visible
        tbNameEnt.Visible = true;
        tbBalaEnt.Visible = true;
        SubDet.Visible = true;

        //set pos to the first empty element of array
        pos = Array.FindIndex(db, i => i == null);
    }

private void SubDet_Click(object sender, EventArgs e)
    {
        string textBox1;
        double textBox2;
        int a = 0011228;
        int b = pos + 1;
        int accNo;

        //get and parse input details
        textBox1 = tbNameEnt.Text;
        textBox2 = double.Parse(tbBalaEnt.Text);

        //allocate account number
        accNo = int.Parse(a.ToString() + b.ToString());

        //set details for new object in array
        db[pos].SetAccount(textBox1, accNo, textBox2); //ERROR HERE

        //print account created confirmation message
        ConfMess();

        //OK button then takes us back to menu
    }

【问题讨论】:

  • 具体发生在哪一行?
  • 改用List&lt;T&gt;
  • “第一个空元素”不存在,因为您在 Form_Load 中设置了所有值,因此没有空条目,因此 pos 为 -1 或其他值。

标签: c# arrays indexing


【解决方案1】:

您使用实例化的 Account 对象初始化您的数组。

不保证 FindIndex() 调用将返回有效位置(即 pos 将被分配 -1)

然后,您可能会引用 db[-1],这会引发异常。

【讨论】:

    【解决方案2】:

    Array.FindIndex 将根据谓词返回位置,如果没有匹配的项目将返回-1,对于您的情况,您在

    中分配数组的每个元素
    for (int i = 0; i < MAX; i++)
           db[i] = new Account();
    

    这将确保没有任何项目为空,因此从 Array.FindIndex 返回 -1,稍后当您使用该位置 pos 访问数组元素时,您会遇到异常。

    这一行:

    pos = Array.FindIndex(db, i => i == null);
    

    稍后会将pos 设置为-1

    db[pos].SetAccount(textBox1, accNo, textBox2);
    

    你会得到异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 2020-12-19
      相关资源
      最近更新 更多