C# lambda 表达式可以有多个语句吗?
C# lambda 表达式可以包含多个语句吗?
(编辑:正如下面的几个答案中所引用的,这个问题最初询问的是“行”而不是“陈述”。)
Can a C# lambda expression include more than one statement?
(Edit: As referenced in several of the answers below, this question originally asked about "lines" rather than "statements".)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
当然:
Sure:
(我假设您实际上谈论的是多个语句而不是多行。)
您可以使用大括号在 lambda 表达式中使用多个语句,但只有不使用大括号的语法才能转换为表达式树:
(I'm assuming you're really talking about multiple statements rather than multiple lines.)
You can use multiple statements in a lambda expression using braces, but only the syntax which doesn't use braces can be converted into an expression tree:
您可以在 lambda 表达式中添加任意数量的换行符; C# 忽略换行符。
您可能想询问多个陈述。
多个语句可以用大括号括起来。
请参阅文档。
You can put as many newlines as you want in a lambda expression; C# ignores newlines.
You probably meant to ask about multiple statements.
Multiple statements can be wrapped in braces.
See the documentation.
自 C# 7 起:
单行语句:
多行语句:
虽然这些被称为本地函数,但我认为这看起来比下面的更干净,并且实际上是相同的
Since C# 7:
Single line statement:
Multiline statement:
although these are called local functions I think this looks a bit cleaner than the following and is effectively the same
来自 Lambda 表达式(C# 编程指南):
From Lambda Expressions (C# Programming Guide):
另一个例子。
Another Example.
使用c#7.0
你也可以这样使用
With c# 7.0
You can use like this also
假设您有一个类:
使用此类中的 C# 7.0,即使没有大括号,您也可以执行此操作:
并且
与以下内容相同:
如果您需要在一行中编写常规方法或构造函数,这也可能会有所帮助,或者当您需要将多个语句/表达式打包到一个表达式中时:
或
或
有关 解构文档中的元组。
Let say you have a class:
With the C# 7.0 inside this class you can do it even without curly brackets:
and
would be the same as:
This also might be helpful if you need to write the a regular method or constructor in one line or when you need more then one statement/expression to be packed into one expression:
or
or
More about deconstruction of tuples in the documentation.