hi I am trying to write an lambda for an event handler. so I can provide more information to the method that gets called.
so I am doing:
button.Click+=new EventHandler ((object sender, EventArgs args) =>
{ button_click (i, sender, args); });
where:
public void button_click (int i, object sender, EventArgs eventArgs)
ok 开发者_JAVA百科so this works as in the method get called, but i
is always the last known value of i
, I really want the value at the point where the lambda is pass to the event. How do you do that?
thanks
Just create a copy of the variable:
int currentI = i;
button.Click+=new EventHandler ((object sender, EventArgs args) =>
{ button_click (currentI, sender, args); });
Note that you've got a certain amount of cruft there. You can write it more simply as:
int currentI = i;
button.Click += (sender, args) => button_click(currentI, sender, args);
Personally I'd rename the button_click
method to conform with .NET naming conventions though.
精彩评论