2

Possible Duplicate:
Why must a lambda expression be cast when supplied as a plain Delegate parameter

Control.Invoke accepts a Delegate parameter type. I cannot pass a lamba expression as a Delegate without telling the compiler which type of delegate I'm passing.

textBox1.Invoke(() => { MessageBox.Show("Hello World"); }); //illegal

In this case, I can cast to Action

textBox1.Invoke((Action)(() => { MessageBox.Show("Hello World"); })); //legal

However, I can create a shorthand method via an extension method (I've seen Marc Gravell do this):

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

Now my shorthand works...

textBox1.Invoke(() => { MessageBox.Show("Hello World"); }); //legal

How is it that the compiler can determine that an anonymous method is an Action in the extension method, but the compiler cannot determine a lamba is an Action and therefore a legal Delegate in the case of Control.Invoke?

4

1 に答える 1

0

First, the compiler is smart enough to determine that the parameter is of type Action (as opposed to say Action<T>). More importantly, the compiler can assume I mean an Action as opposed to an Expression because the ambiguity is removed. If I do something silly to recreate ambiguity...say create an overload via a new extension method:

    public static void Invoke(this Control control, Expression<Action> action)
    {
        Console.WriteLine("hi");
        //control.Invoke((Delegate)action);
    }

The compiler will catch that as well:

The call is ambiguous between the following methods or properties:

The comments made walked me to the answer I'm looking for.

于 2013-01-23T19:25:35.770 に答える