关闭C#事件处理程序代理? [英] Closures in C# event handler delegates?
问题描述
我有以下代码动态生成获取匿名事件处理程序的按钮:
for(int i = 0; i< 7; i ++)
{
Button newButton = new Button();
newButton.Text =点击我!;
newButton.Click + = delegate(Object sender,EventArgs e)
{
MessageBox.Show(I'm button number+ i);
};
this.Controls.Add(newButton);
}
我预计文字我是按钮编号在for循环的迭代中,+ i
被关闭,值为 i
。但是,当我实际运行程序时,每个按钮都说我是按钮号码7
。我失踪了什么我正在使用VS2005。
编辑:所以我想我的下一个问题是,如何捕获这个值?
要获得此行为,您需要在本地复制变量,而不是使用迭代器:
for(int i = 0; i< 7; i ++)
{
var inneri = i;
按钮newButton = new Button();
newButton.Text =点击我!;
newButton.Click + = delegate(Object sender,EventArgs e)
{
MessageBox.Show(我是按钮号+ inneri);
};
this.Controls.Add(newButton);
}
更详细地讨论推理,此问题。
I am coming from a functional-programming background at the moment, so forgive me if I do not understand closures in C#.
I have the following code to dynamically generate Buttons that get anonymous event handlers:
for (int i = 0; i < 7; i++)
{
Button newButton = new Button();
newButton.Text = "Click me!";
newButton.Click += delegate(Object sender, EventArgs e)
{
MessageBox.Show("I am button number " + i);
};
this.Controls.Add(newButton);
}
I expected the text "I am button number " + i
to be closed with the value of i
at that iteration of the for loop. However, when I actually run the program, every Button says I am button number 7
. What am I missing? I am using VS2005.
Edit: So I guess my next question is, how do I capture the value?
To get this behavior, you need to copy the variable locally, not use the iterator:
for (int i = 0; i < 7; i++)
{
var inneri = i;
Button newButton = new Button();
newButton.Text = "Click me!";
newButton.Click += delegate(Object sender, EventArgs e)
{
MessageBox.Show("I am button number " + inneri);
};
this.Controls.Add(newButton);
}
The reasoning is discussed in much greater detail in this question.
这篇关于关闭C#事件处理程序代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!