C# Lambda 函数:返回数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15525412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:03:37  来源:igfitidea点击:

C# Lambda Functions: returning data

c#.netdelegatesanonymous-functionlambda

提问by Drew R

Am I missing something or is it not possible to return a value from a lambda function such as..

我是不是遗漏了什么,或者是不可能从 lambda 函数返回一个值,比如..

Object test = () => { return new Object(); };

Object test = () => { return new Object(); };

or

或者

string test = () => { return "hello"; };

string test = () => { return "hello"; };

I get a build error "Cannot convert lambda expression to type 'string' because it is not a delegate type".

我收到构建错误“无法将 lambda 表达式转换为类型‘字符串’,因为它不是委托类型”。

It's like this syntax assigns the lambda rather than the result of the lambda, which I did not expect. I can achieve the desired functionality by assigning the function to a Func and calling it by name, but is that the only way?

就像这个语法分配了 lambda 而不是 lambda 的结果,这是我没想到的。我可以通过将函数分配给 Func 并按名称调用它来实现所需的功能,但这是唯一的方法吗?

Please no "why would you need to do this?" regarding my example.

请不要“你为什么需要这样做?” 关于我的例子。

Thanks in advance!

提前致谢!

采纳答案by Konrad Rudolph

It's possible but you are trying to assign a lambda to a string. – You need to invokethe lambda:

这是可能的,但您正在尝试将 lambda 分配给string. – 您需要调用lambda:

Func<string> f = () => { return "hello"; };
string test = f();

The error message actually says it all:

错误消息实际上说明了一切:

Cannot convert lambda expression to type 'string'

无法将 lambda 表达式转换为“字符串”类型

… that's exactly the issue here.

……这正是这里的问题。

If you want to invoke the lambda inline –?but really: why??– you can do that too, you just need to first make it into a delegate explicitly:

如果您想内联调用 lambda -? 但实际上:为什么??- 您也可以这样做,您只需要首先将其显式设置为委托:

string test = (new Func<string>(() => { return "hello"; }))();