Define a lambda function and execute it immediately

前端 未结 2 1224
粉色の甜心
粉色の甜心 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:20

    You're not "defining a lambda".. you're wrapping parenthesis around what you think is one.

    The compiler doesn't infer this type of thing. It needs context. You give it context by assigning or casting the representation of the lambda to a delegate type:

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

    Thats clear context. If you want an unclear one.. this sort of thing also works:

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

提交回复
热议问题