C#lambda表达式,范围变量值

问题描述

| 嗨,我正在尝试为事件处理程序编写一个lambda。因此,我可以为所调用方法提供更多信息。 所以我在做:
button.Click+=new EventHandler ((object sender,EventArgs args) => 
{ button_click (i,sender,args); });
哪里:
public void button_click (int i,object sender,EventArgs eventArgs)
好的,所以可以像调用方法中那样工作,但是
i
始终是
i
的最后一个已知值,我真的很想在将lambda传递给事件的点上使用该值。你是怎样做的? 谢谢     

解决方法

        只需创建变量的副本:
int currentI = i;
button.Click+=new EventHandler ((object sender,EventArgs args) => 
    { button_click (currentI,sender,args); });
请注意,那里有一定数量的残留物。您可以将其编写为:
int currentI = i;
button.Click += (sender,args) => button_click(currentI,args);
我个人将重命名
button_click
方法以符合.NET命名约定。