开发者

lambda -> delegate doesn't compile

开发者 https://www.devze.com 2023-03-12 23:54 出处:网络
The last statement does not compile. please refer to the comments along with the code for the detail of my question.

The last statement does not compile. please refer to the comments along with the code for the detail of my question.

class Test
{
    private static voi开发者_开发知识库d Foo(Delegate d){}

    private static void Bar(Action a){}

    static void Main()
    {
        Foo(new Action(() => { Console.WriteLine("a"); })); // Action converts to Delegate implicitly

        Bar(() => { Console.WriteLine("b"); }); // lambda converts to Action implicitly

        Foo(() => { Console.WriteLine("c"); }); // Why doesn't this compile ? (lambda converts to Action implicitly, and then Action converts to Delegate implicitly)
    }
}


Because the .net compiler doesn't know what type of delegate to turn the lambda into. It could be an Action, or it could be a void MyDelegate().

If you change it as follows, it should work:

Foo(new Action(() => { Console.WriteLine("c"); }));


Why should the compiler know how to two-step: from lambda -> Action -> Delegate?

This compiles:

class Test
{
    private static void Foo(Delegate d) { }

    private static void Bar(Action a) { }

    static void Main()
    {
        Foo(new Action(() => { Console.WriteLine("world2"); })); // Action converts to Delegate implicitly

        Bar(() => { Console.WriteLine("world3"); }); // lambda converts to Action implicitly

        Foo((Action)(() => { Console.WriteLine("world3"); })); // This compiles
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消