我有"索引超出了数组的范围"错误

时间:2014-04-09 09:20:07

标签: c#

当我点击button3和button4时,我有问题 我不知道我做错了什么 看起来我的程序试图让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]));
        }
    }

}

}

1 个答案:

答案 0 :(得分:0)

我认为问题是所有数组都在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();
}