Problem description
C#2.0 has an anonymous approach, which in part saves us the effort to maintain the context of the code, and does not need to think about what it would be appropriate to name a method. In some methods of the FCL, it is required to pass in a parameter of type delegate, 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 an anonymous method, you need to declare a delegate void DoSomething () method above the code, and then you can implement DoSomething () in the Invoke method with a lambda expression or a delegate.
0 delegate void DoSomething ();
1
2 private void App ()
3 {
4 Xxcontrol.invoke (New dosomething () =
5 {
6//dosomething specific operations
7}));
8}
This can be done, but using an anonymous method is better, at least it looks more concise.
0 private void App ()
1 {
2 Xxcontrol.invoke (delegate
3 {
4//dosomething Specific operations
5});
6}
The above code will be error when compiling: Cannot convert anonymous method to type System.Delegate because it was not a Delegate type. The method requires that the parameter is a delegate (delegate) type, and now passes only an anonymous method. The most fundamental reason for this error is that when the compiler is dealing with anonymous methods, it is not possible to infer what type the delegate's method returns, and what kind of delegate is returned.
The solution to solve the above problem is essentially specifying what type of delegate this anonymous method will return, in several ways:
1. Use Methodinvoke or action
0 private void App ()
1 {
2 Xxcontrol.invoke ((MethodInvoker) delegate ()
3 {
4//dosomething Specific operations
5});
6} 0 private void App ()
1 {
2 Xxcontrol.invoke (Action) delegate ()
3 {
4//dosomething Specific operations
5});
6}
Both Methodinvoke and action are methods that return a delegate with a null type.
2. You can define an invoke extension method for the control
0 public static void Invoke (this control control, action action)
1 {
2 control. Invoke ((Delegate) action);
3}
This can be called when it is called:
0//Use delegate
1 Xxcontrol.invoke (Delegate {//dosomething here});
2//using lambda expression
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/
C # anonymous method and delegate type conversion error