为什么分号而不是空块并不总是有效?

Why is a semi-colon instead of an empty block not always valid?

我想这个问题已经有一段时间了;为什么使用分号 ; 而不是空块 {} 并不总是有效?它在 whileforifelse 等语句上使用时有效。但它不适用于 trycatch , finallydelegate(留空可能不太有用)。

所以做这样的事情是有效的:

while(shouldIWait()); // This is normal

try {
    doThing(); // Might throw an exception
} catch { } // Ignore the exception

但这不会:

try {
    doThing(); // Might throw an exception
} catch; // Syntax error!

根据我的理解,分号总是可以用来代替空块。为什么这仅限于某些陈述?在语句后面使用 { }; 之间有真正的区别吗?

在某些情况下,代码块是可选的,在某些情况下是必需的。

如果是 class 或结构的方法,则需要一段代码(除非它是抽象或部分方法)。

如果发生捕获,还需要一段代码(用于处理异常)。创建一个空的 catch 块被认为是糟糕的编程。

正如@JeppeStigNielsen 解释的那样:

It is required by the C# Specification. See chapter 8, Statements. Specifically, the if statement (section 8.7.1) contains an embedded-statement while a try statement (section 8.10) contains a block. An embedded-statement can be any of a number of things, only one of which is a block (8.2). Another is an empty-statement (8.3). See the beginning of Chapter 8 for these definitions.

据我所知[文档是 ifwhile 等语句。期望任何类型的嵌入式语句。这些是块 { }、空语句 ; 等。try 语句需要一个块,而不仅仅是任何嵌入语句(参见第 8 章开头)。

文档可以下载 directly from Microsoft 或在您的本地硬盘驱动器 C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Specifications33\ 上找到(来自@JeppeStigNielsen)。