Problem description
C #2.0 has an anonymous method, which saves us some maintenanceCodeYou 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:
Public object invoke (delegate method); 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 ().
Delegate void dosomething (); Private void app () {xxcontrol. Invoke (New dosomething () =>{// dosomething specific operation }));}
This can be done, but it is better to use the anonymous method, at least it looks more concise.
Private void app () {xxcontrol. Invoke (delegate {// dosomething specific operation });}
The above code will go wrong 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
Private void app () {xxcontrol. Invoke (methodinvoker) Delegate () {// dosomething specific operation });}
Private void app () {xxcontrol. Invoke (Action) Delegate () {// dosomething specific action });}
Both methodinvoke and action are delegate with empty return type of method.
2. You can define an invoke extension method for control.
Public static void invoke (this control, action Action) {control. Invoke (delegate) action );}
You can call it as follows:
// Use delegate xxcontrol. Invoke (delegate {// dosomething here}); // use Lambda expression 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/