0

如果我单击 btn1 数组 1(生成)的包含将改变。我想要做的是:点击btn2(重置btn)后想要将数组2(n)的元素复制到array1(生成)但我收到这个错误:目标数组不够长。检查 destIndex 和长度,以及数组的下限。

 public partial class Form1 : Form
    {
        string[] generate = new string[20]   {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Name14","Name15","Name16","Name17","Name18","Name19","Name20" };
        string[] n = new string[] { "Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10", "Name11", "Name12", "Name13", "Name14", "Name15", "Name16", "Name17", "Name18", "Name19", "Name20" };

    string name;
    int Num;

    public Form1()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e) // START btn
    {
        Num = int.Parse(textBox1.Text) - 1;
        if (Num < 20)
        {
            if (generate.Length > Num)
            {

                for (int i = Num; i >= 0; i--)
                {

                    name = generate.ElementAt(i);
                    listBox1.Items.Add(name); // Print it to list1 
                    generate = generate.Where(s => s != name).ToArray(); // Delete name after using
                }
            }
            else MessageBox.Show("Sorry, remaining names =" + generate.Length);
            listBox2.Items.Clear();
            listBox2.Items.AddRange(generate);

        }
        else MessageBox.Show("Max name is 20!");

    }

    private void button2_Click(object sender, EventArgs e) // Reset btn
    {
        listBox1.Items.Clear();
        listBox2.Items.Clear();
        textBox1.Clear();
        Array.Copy(n, 0, generate, 0, 20);

    }
}

}

4

2 回答 2

2

您可以使用 LINQ 复制数组。

  var array2 =  array1.ToList().ToArray()

如果您使用.Copy方法,请确保您的范围是正确的

于 2013-06-16T00:02:30.643 回答
0

当您单击按钮 1 时,以下行正在为大小小于 20 的生成变量创建一个新数组:

generate = generate.Where(s => s != name).ToArray(); // Delete name

因此,当您调用按钮 2 时,您正在尝试从大小为 20 的数组 n 复制到generate大小小于 20 的数组。

于 2013-06-16T00:15:21.853 回答