anonymous-methods

Anonymous method in Invoke call

六眼飞鱼酱① 提交于 2019-11-26 04:07:09
问题 Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke. We have tried a number of different approaches, all to no avail. For example: myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); }); where someParameter is local to this method The above will result in a compiler error: Cannot convert anonymous method to type \'System.Delegate\' because it is not a delegate type 回答1: Because Invoke / BeginInvoke accepts

delegate keyword vs. lambda notation

时光怂恿深爱的人放手 提交于 2019-11-26 01:38:46
问题 Once it is compiled, is there a difference between: delegate { x = 0; } and () => { x = 0 } ? 回答1: Short answer : no. Longer answer that may not be relevant: If you assign the lambda to a delegate type (such as Func or Action ) you'll get an anonymous delegate. If you assign the lambda to an Expression type, you'll get an expression tree instead of a anonymous delegate. The expression tree can then be compiled to an anonymous delegate. Edit: Here's some links for Expressions. System.Linq

Unsubscribe anonymous method in C#

自作多情 提交于 2019-11-25 23:15:38
问题 Is it possible to unsubscribe an anonymous method from an event? If I subscribe to an event like this: void MyMethod() { Console.WriteLine(\"I did it!\"); } MyEvent += MyMethod; I can un-subscribe like this: MyEvent -= MyMethod; But if I subscribe using an anonymous method: MyEvent += delegate(){Console.WriteLine(\"I did it!\");}; is it possible to unsubscribe this anonymous method? If so, how? 回答1: Action myDelegate = delegate(){Console.WriteLine("I did it!");}; MyEvent += myDelegate; // ...

Is there a reason for C#'s reuse of the variable in a foreach?

你说的曾经没有我的故事 提交于 2019-11-25 22:20:46
问题 When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example: foreach (var s in strings) { query = query.Where(i => i.Prop == s); // access to modified closure ... } Due to the modified closure, the above code will cause all of the Where clauses on the query to be based on the final value of s . As explained here, this happens because the s variable declared in foreach loop above is translated like this in the compiler: