我有“;索引在数组“”的边界之外;错误

本文关键字:边界 错误 数组 索引 我有 | 更新日期: 2023-09-27 17:57:36

单击按钮3和按钮4时出现问题我不知道我做错了什么看起来我的程序试图将threadArray放在除了索引之外的位置

ps我的英语不好,但我能读很好的

    Thread[] threadArray;
    int numberThread;
    public delegate void myDelegate(int x);
    myDelegate[] myDelegates;
    int[] numberOfIterations;
    public Form1()
    {
        InitializeComponent();
        comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        comboBox1.SelectedIndex = 0;
        comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
        comboBox2.Enabled = false;
        comboBox3.Enabled = false;
        numericUpDown2.Enabled = false;
        comboBox3.Items.Add("product");
        comboBox3.SelectedIndex = 0;
    }
    private void button1_Click(object sender, EventArgs e)
    {
        threadArray = new Thread[(int)numericUpDown1.Value];
        numberThread = (int)numericUpDown1.Value;
        myDelegates = new myDelegate[(int)numericUpDown1.Value];
        numericUpDown1.Enabled = false;
        numberOfIterations = new int[numberThread];
        for (int i = 0; i < numberThread; i++)
        {
            comboBox2.Items.Add(i+1);
        }
        comboBox2.Enabled = true;
        button1.Enabled = false;
    }
    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        comboBox3.Enabled = true;
        numericUpDown2.Enabled = true;
    }
    private void button2_Click(object sender, EventArgs e)
    {
        int x = Convert.ToInt32(comboBox2.SelectedItem);
        x = x - 1;
        numberOfIterations[x] = (int)numericUpDown2.Value;
        if (comboBox3.SelectedIndex == 0)
        {
            myDelegates[x] = null;
            myDelegates[x] += Functions.productDev;
        }
        threadArray[x] = new Thread(()=>myDelegates[x]((int)numericUpDown2.Value));
    }
    private void button4_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < numberThread; i++)
        {
            threadArray[i].Start();
        }
    }
    private void button3_Click(object sender, EventArgs e)
    {
        for (int j = 0; j < numberThread; j++)
        {
            numberOfIterations[j] = (int)numericUpDown2.Value;
            if (comboBox3.SelectedIndex == 0)
            {
                myDelegates[j] = null;
                myDelegates[j] += Functions.productDev;
            }
            threadArray[j] = new Thread(() => myDelegates[j](numberOfIterations[j]));
        }
    }
}

}

我有“;索引在数组“”的边界之外;错误

我认为问题是所有数组都在button1_Click事件中初始化。如果你没有按Button1怎么办。而是在构造函数中初始化它们。

public void InitValues()
{
    threadArray = new Thread[(int)numericUpDown1.Value];
    numberThread = (int)numericUpDown1.Value;
    myDelegates = new myDelegate[(int)numericUpDown1.Value];
    numericUpDown1.Enabled = false;
    numberOfIterations = new int[numberThread];
}

在构造函数中调用此函数,并从Button1_Click事件中删除此代码平静。

public Form1()
{
    //..............
    InitValues();
}