Closures in C# event handler delegates?(C# 事件处理程序委托中的闭包?)
问题描述
目前我来自函数式编程背景,如果我不了解 C# 中的闭包,请见谅.
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 am button number" + i
在 for 循环的迭代中以 i
的值关闭.但是,当我实际运行程序时,每个 Button 都会显示 I am button number 7
.我错过了什么?我用的是VS2005.
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.
所以我想我的下一个问题是,我如何捕获价值?
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# 事件处理程序委托中的闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 事件处理程序委托中的闭包?


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01