C anonymous method and Delegate type conversion error analysis

  • 2020-12-09 00:58:22
  • OfStack

An example of C# anonymous method and Delegate type conversion error is analyzed. Share to everybody for everybody reference. The specific analysis is as follows:

Problem description

The advent of anonymous methods in C#2.0 saved us a degree of effort in maintaining the context of the code and in thinking about the appropriate name for a method. In some methods of FCL, it is required to pass in a parameter of type Delegate, such as Control.Invoke or Control.BeginInvoke methods:

public object Invoke(Delegate method);
public IAsyncResult BeginInvoke(Delegate method);

In this case, if you do not use anonymous methods, you need to declare an delegate void DoSomething() method at the top of the code, and then implement DoSomething() in the Invoke method using an lambda expression or delegate.

delegate void DoSomething(); 
private void App()
{
    XXControl.Invoke(new DoSomething(() =>
    {
        //DoSomething Specific operation of
    }));
}

This can be done, but it's better to use anonymous methods, or at least to make them seem cleaner.

private void App() 
{
    XXControl.Invoke(delegate
    {
        //DoSomething Specific operation of
    });
}

Cannot convert anonymous method to type Delegate because it is a delegate type anonymous method to type because it is a delegate type. The method requires a delegate (delegate) type of argument, and now only an anonymous method is passed. The fundamental reason for this error is that the compiler, while working with anonymous methods, cannot infer what type the delegate method returns, and therefore does not know what kind of delegate it returns.

The solution

To solve the above problem, which is basically to specify what type of delegate this anonymous method will return, there are several ways:

Use MethodInvoke or Action

private void App() 
{
    XXControl.Invoke((MethodInvoker)delegate()
    {
        //DoSomething Specific operation of
    });
}
private void App()
{
    XXControl.Invoke((Action)delegate()
    {
        //DoSomething Specific operation of
    });
}

Both MethodInvoke and Action are delegates whose method return type is null.

2. An Invoke extension method can be defined for Control

public static void Invoke(this Control control, Action action) 
{
    control.Invoke((Delegate)action);
}

When it is called, it can be called as follows:

// Commissioned by using  
XXControl.Invoke(delegate { //DoSomething  here});
// use lambda expression
XXControl.Invoke(()=>{ //DoSomething here});

Hopefully this article has been helpful for your C# programming.


Related articles: