int num = 0; String name = textBox1.Text.Trim(); if (name.Equals(string.Empty)) { MessageBox.Show("你看看你输入了吗,还点写入"); textBox1.Focus(); } else { List<String> vs = new List<string>(); vs.Add(textBox1.Text); MessageBox.Show(""+vs.Count); if(MessageBox.Show("还要写入吗", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK) { textBox1.Text = ""; textBox1.Focus(); return; } else { Form2 form2 = new Form2(vs); this.Hide(); form2.ShowDialog(); this.Dispose(); } }这个代码取集合的时候为什么显示只有一个集合
时间: 2024-01-23 15:02:14 浏览: 183
在上述代码中,`List<String> vs = new List<string>();` 在每次执行 `else` 语句块时都会创建一个新的空列表。因此,当你向列表中添加元素后,`MessageBox.Show(""+vs.Count);` 显示的结果只能是1,因为此时列表中只有一个元素。
为了解决这个问题,你需要在每次执行 `else` 语句块时使用同一个列表。可以将列表定义为类成员变量或者静态变量,或者将其作为参数传递给其他方法。以下是一个可能的解决方案:
```csharp
private List<String> vs = new List<string>(); // 定义一个类成员变量
private void button1_Click(object sender, EventArgs e)
{
String name = textBox1.Text.Trim();
if (name.Equals(string.Empty))
{
MessageBox.Show("你看看你输入了吗,还点写入");
textBox1.Focus();
}
else
{
vs.Add(textBox1.Text); // 向列表中添加元素
MessageBox.Show("" + vs.Count);
if (MessageBox.Show("还要写入吗", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
{
textBox1.Text = "";
textBox1.Focus();
return;
}
else
{
Form2 form2 = new Form2(vs);
this.Hide();
form2.ShowDialog();
this.Dispose();
}
}
}
```
在上述代码中,`List<String> vs` 被定义为一个类成员变量,并在每次执行 `else` 语句块时向其中添加元素。这样,`MessageBox.Show(""+vs.Count);` 就能正确地显示列表中元素的数量了。
阅读全文