如果我点击btn1,数组1(生成)的包含将会改变。我想要做的是:点击btn2(重置btn)后想要将数组2(n)的元素复制到array1(生成),但我收到此错误: 目标数组不够长。检查destIndex和length,以及数组的下限。
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);
}
}
}
答案 0 :(得分:2)
您可以使用LINQ复制数组。
var array2 = array1.ToList().ToArray()
如果您使用.Copy
方法,请确保您的范围正确
答案 1 :(得分:0)
单击按钮1时,以下行为生成变量创建一个大小小于20的新数组:
generate = generate.Where(s => s != name).ToArray(); // Delete name
因此,当您调用按钮2时,您尝试从大小为20的数组n复制到大小小于20的数组generate
。