简体   繁体   English

Lambda表达式中的花括号与无花括号C#

[英]Curly brackets vs no curly brackets in lambda expression c#

I am pretty new to C#, around 1 year experience. 我是C#的新手,大约有1年的经验。 Recently got introduced to lambda expressions. 最近介绍了lambda表达式。 I want to have an Action<string> which would display an Error with custom Error text to a MessageBox. 我想有一个Action<string> ,它将在MessageBox中显示带有自定义错误文本的错误。 I am wondering, what is the difference between: 我想知道,两者之间有什么区别?

public static Action<string> Error = s => { MessageBox.Show(s, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); };

and

public static Action<string> Error = s => MessageBox.Show(s, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

Thanks for any helpful advises :) 感谢您的帮助:)

According to official C# language specification: 根据官方的C#语言规范:

8.2 Blocks 8.2方块

A block permits multiple statements to be written in contexts where a single statement is allowed. 块允许在允许单个语句的上下文中编写多个语句。

block:
    {   statement-listopt   }

A block consists of an optional statement-list (§8.2.1), enclosed in braces. 块由一个可选的语句列表(第8.2.1节)组成,并用大括号括起来。 If the statement list is omitted, the block is said to be empty. 如果省略了语句列表,则该块为空。

A block may contain declaration statements (§8.5). 块可以包含声明语句(第8.5节)。 The scope of a local variable or constant declared in a block is the block. 块中声明的局部变量或常量的范围是该块。

Within a block, the meaning of a name used in an expression context must always be the same (§7.6.2.1). 在一个块内,表达式上下文中使用的名称的含义必须始终相同(第7.6.2.1节)。

A block is executed as follows: 块执行如下:

• If the block is empty, control is transferred to the end point of the block. •如果该块为空,则控制权转移到该块的终点。

• If the block is not empty, control is transferred to the statement list. •如果块不为空,则控制权转移到语句列表。

When and if control reaches the end point of the statement list, control is transferred to the end point of the block. 当且如果控制到达语句列表的终点,则控制将转移到块的终点。

The statement list of a block is reachable if the block itself is reachable. 如果块本身可访问,则该块的语句列表可访问。

The end point of a block is reachable if the block is empty or if the end point of the statement list is reachable. 如果块为空或语句列表的终点是可到达的,则该块的终点是可到达的。

The difference is only syntactical, it has no impact on the code that executes. 区别只是语法上的,对执行的代码没有影响。 The same thing is compiled using either notation. 使用任何一种表示法编译相同的东西。

After an => , you may either write a block statement, which is surrounded by { and } . => ,您可以编写一个被{}包围的block语句。 You may also write a single expression 'line of code' and omit the curly braces, to prevent boilerplate curly braces. 您也可以编写单个表达式 “代码行”并省略花括号,以防止重复使用花括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM