public partial class Form1 : Form
{
public List<TextBox> textBoxInputList;
public void Form1_Load(object sender, EventArgs e)
{
List<TextBox> textBoxInputList = new List<TextBox>() {textBox1};
}
private void ButtonCleanInput_Click(object sender, EventArgs e)
{
List<TextBox> textBoxInputList = new List<TextBox>() {textBox1};
//在这里还要再实例化一次textBoxInputList
}
}
已经设置为public List,在方法Form-load使用textBoxInputList没问题,但是在别的方法里,比如在方法ButtonCleanInput-Click,必须重写
List<TextBox> textBoxInputList = new List<TextBox>() {textBox1};
否则textBoxInputList里面是空的,报错如下
请问如何new 一个
List<TextBox> textBoxInputList
,然后在别的方法里都能调用?
编程新手,不懂轻喷
List<TextBox> textBoxInputList = new List<TextBox>() {textBox1};
这么写,等于定义了一个也叫textBoxInputList 的重名的局部变量,隐藏了成员变量textBoxInputList
所以textBoxInputList 还是null
应该写
textBoxInputList = new List<TextBox>() {textBox1}; //去掉List<TextBox>
另外,也可以在成员函数定义的时候就初始化下
public List<TextBox> textBoxInputList = new List<TextBox>();
那么 form_load里面可以写
textBoxInputList.Add(textBox1);
不用写textBoxInputList = new List<TextBox>() {textBox1};了。
首先得搞清楚全局变量和局部变量的概念,另外要搞清楚winforms里窗体事件及控件事件的含义,比方这里的Form1_Load表示窗体加载事件处理方法,而ButtonCleanInput_Click表示按钮点击处理方法。总之得把基本原理掌握了,才能写起来游刃有余,磨刀不误砍柴工,不要急于写代码。