开发者

C# lambda expression, scoped variable value

开发者 https://www.devze.com 2023-03-08 23:11 出处:网络
hi I am trying to write an lambda for an event handler. so I can provide more information to the method that gets called.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消