我目前正在尝试向标签数组添加特定操作,但变量仅保留在{}
.
_arr[i].Click += (a, b) => {
z++;
numarfinal = Convert.ToString(z);
MessageBox.Show(Convert.ToString(numarfinal));
};
外部{}
既没有变量z
也没有numarfinal
改变,但MessageBox.Show
报告他们的参数已经改变。
这是整个功能:
Label[] _arr = new Label[20];
Label[] _dinamic = new Label[20];
private static Random _r = new Random();
string numarfinal ;
private void button1_Click(object sender, EventArgs e)
{
int z=0;
int limita = Convert.ToInt16(textBox1.Text);
limita = int.Parse(textBox1.Text);
if (limita > 20)
textBox1.Text = "Do sth";
int randomnumber = _r.Next(20);
for(int i=0;i<limita;i++)
{
do
{
randomnumber = _r.Next(20);
} while (randomnumber==0);
_arr[i] = new Label();
_arr[i].Click += (a, b) =>
{
z++;
numarfinal= Convert.ToString(z);
MessageBox.Show(Convert.ToString(numarfinal));
};
_arr[i ].Text = Convert.ToString(randomnumber);
_arr[i ].Size = new Size(50,50);
_arr[i ].Location = new Point(55*i,60);
testlabel.Text = Convert.ToString(numarfinal); // the label value remain nothing (numarfinal's initial value)
this.Controls.Add(_arr[i]);
}