在 WPF 按钮单击事件上使用 lambda 表达式时出现奇怪的行为
我的问题很难解释,所以我创建了一个例子在这里展示。
当显示下例中的 WPF 窗口时,会显示三个按钮,每个按钮都有不同的文本。
当单击这些按钮中的任何一个时,我认为其文本应该显示在消息中,但相反,所有按钮都显示相同的消息,就好像它们都使用最后一个按钮的事件处理程序一样。
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
var stackPanel = new StackPanel();
this.Content = stackPanel;
var n = new KeyValuePair<string, Action>[] {
new KeyValuePair<string, Action>("I", () => MessageBox.Show("I")),
new KeyValuePair<string, Action>("II", () => MessageBox.Show("II")),
new KeyValuePair<string, Action>("III", () => MessageBox.Show("III"))
};
foreach (var a in n) {
Button b = new Button();
b.Content = a.Key;
b.Click += (x, y) => a.Value();
stackPanel.Children.Add(b);
}
}
}
有谁知道出了什么问题吗?
My problem is hard to explain, so I created an example to show here.
When the WPF window in the example below is shown, three buttons are displayed, each one with a different text.
When anyone of these buttons is clicked, I assume its text should be displayed in the message, but instead, all of them display the same message, as if all of them were using the event handler of the last button.
public partial class Window1 : Window {
public Window1() {
InitializeComponent();
var stackPanel = new StackPanel();
this.Content = stackPanel;
var n = new KeyValuePair<string, Action>[] {
new KeyValuePair<string, Action>("I", () => MessageBox.Show("I")),
new KeyValuePair<string, Action>("II", () => MessageBox.Show("II")),
new KeyValuePair<string, Action>("III", () => MessageBox.Show("III"))
};
foreach (var a in n) {
Button b = new Button();
b.Content = a.Key;
b.Click += (x, y) => a.Value();
stackPanel.Children.Add(b);
}
}
}
Does anyone know what is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为编译器在循环中评估闭包的方式:
编译器假设您在闭包中需要
a
的上下文,因为您正在使用a.Value
,因此它正在创建一个使用a
值的 lambda 表达式。 但是,a
的作用域涵盖整个循环,因此它只会分配最后一个值。为了解决这个问题,您需要将
a
复制到循环内的变量,然后使用它:It is because of how closures are evaluated compiler in the loop:
The compiler assumes that you will need the context of
a
in the closure, since you are usinga.Value
, so it is creating one lambda expression that uses the value ofa
. However,a
has scope across the entire loop, so it will simply have the last value assigned to it.To get around this, you need to copy
a
to a variable inside the loop and then use that:不直观,是吧? 原因是 lambda 表达式如何从表达式外部捕获变量。
当 for 循环最后一次运行时,变量
a
被设置为数组n
中的最后一个元素,此后它就不再被触及。 但是,附加到事件处理程序(返回a.Value()
)的 lambda 表达式实际上尚未计算。 因此,当它运行时,它将获取a
的当前值,此时它是最后一个元素。在不使用一堆额外变量等的情况下,使其按照您期望的方式工作的最简单方法可能会更改为如下所示:
Unintuitive, huh? The reason is because of how lambda expressions capture variables from outside the expression.
When the for loop runs for the last time, the variable
a
is set to the last element in the arrayn
, and it never gets touched after that. However, the lambda expression attached to the event handler, which returnsa.Value()
, hasn't actually been evaluated yet. As a result, when it does run, it'll then get the current value ofa
, which by then is the last element.The easiest way to make this work the way you expect it to without using a bunch of extra variables and so forth would probably to change to something like this:
要解决此问题,请执行以下操作:
To fix this do the following: