How to return value with anonymous method?

后端 未结 6 583
生来不讨喜
生来不讨喜 2020-12-07 13:26

This fails

string temp = () => {return \"test\";};

with the error

Cannot convert lambda expression to type \'str

6条回答
  •  春和景丽
    2020-12-07 13:55

    Using a little helper function and generics you can let the compiler infer the type, and shorten it a little bit:

    public static TOut FuncInvoke(Func func)
    {
        return func();
    }
    
    var temp = FuncInvoke(()=>"test");
    

    Side note: this is also nice as you then are able to return an anonymous type:

    var temp = FuncInvoke(()=>new {foo=1,bar=2});
    

提交回复
热议问题