Define a lambda function and execute it immediately

前端 未结 2 1182
粉色の甜心
粉色の甜心 2021-02-08 13:30

I\'m defining a lambda and calling it, by appending \"()\", immediately.

Try:

int i = (() => 0) ();

Error:

Er

2条回答
  •  无人共我
    2021-02-08 14:06

    A lambda just does not support being executed. A delegate supports being executed. A lambda expression can be implicitly converted to a delegate type. In case no such conversion is requested there is no "default" delegate type. Since .NET 2 we normally use Action and Func for everything but we could use different delegate types.

    First convert to a delegate, then execute:

    ((Func)(() => 0))()
    

    One could argue that C# should default to using Action and Func if nothing else was requested. The language does not do that as of C# 5.

提交回复
热议问题