Problem description
C #2.0 shows the html "target = _ blank> anonymous method, which saves us some effort to maintain the code context, you do not need to think about the proper name for a method. in some FCL methods, a Delegate parameter is required, such as Control. invoke or Control. beginInvoke method:
0 public object Invoke (Delegate method );
1 public IAsyncResult BeginInvoke (Delegate method );
In this case, if you do not use the anonymous method, you must first declare a delegate void DoSomething () method on the code, then, you can use a lambda expression or delegate in the Invoke method to implement DoSomething ().
0 delegate void DoSomething ();
1
2 private void App ()
3 {
4 XXControl. Invoke (new DoSomething () =>
5 {
6 // perform the DoSomething operation
7 }));
8}
This can be done, but it is better to use the anonymous method, at least it looks more concise.
0 private void App ()
1 {
2 XXControl. Invoke (delegate
3 {
4 // DoSomething operations
5 });
6}
The above code will cause an error during compilation: Cannot convert anonymous method to type System. delegate because it is not a delegate type. the method requires that the parameter be of the delegate type, but now only an anonymous method is passed. the most fundamental cause of this error is that when the compiler processes anonymous methods, it cannot infer the type returned by the delegate method, so it does not know what kind of delegate is returned.
Solution
To solve the problem above, basically it is to specify the type of delegation that the anonymous method will return. There are several methods:
1. Use MethodInvoke or Action
0 private void App ()
1 {
2 XXControl. Invoke (MethodInvoker) delegate ()
3 {
4 // DoSomething operations
5 });
6}
0 private void App ()
1 {
2 XXControl. Invoke (Action) delegate ()
3 {
4 // DoSomething operations
5 });
6}
Both MethodInvoke and Action are delegate with empty return type of method.
2. You can define an Invoke extension method for Control.
0 public static void Invoke (this Control control, Action action)
1 {
2 control. Invoke (Delegate) action );
3}
You can call it as follows:
0 // use the delegate
1 XXControl. Invoke (delegate {// DoSomething here });
2 // use lambda expressions
3 XXControl. Invoke () =>{// DoSomething here });
Reference
1. http://stackoverflow.com/questions/253138/anonymous-method-in-invoke-call
2. http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/