[英]why do some lines not have semicolon in C#?
我只是想弄清楚為什么在下面的一些行不以分號結束但其他行做的技術原因 - 它是什么關於C#在某些行中預期的分號呢?
事實上,在寫這篇文章時,我注意到必須帶有大括號{}的語句不需要分號,但是自己的“Console.WriteLine”中的行確實需要它。
真的試圖找到這個的技術原因......
即:
namespace checkPackage **//no semicolon**
{
class Program **//no semicolon**
{
static void Main(string[] args) **//no semicolon**
{
listFilesInDirectory(@"C:\Temp\"); **//NEEDS a semicolon**
}
static void listFilesInDirectory(string workingDirectory) **//no semicolon**
{
string[] filePaths = Directory.GetFiles(workingDirectory); **//NEEDS a semicolon**
foreach (string filePath in filePaths) **//no semicolon**
{
Console.WriteLine(filePath); **//NEEDS a semicolon**
}
}
}
}
分號不是行終止符......它是一個語句終止符。 每個表達式語句和聲明語句的末尾都有一個分號。
( if
, for
etc語句不是表達式或聲明語句。)
例如:
public class Foo // Part of a class declaration
{
int x = 0; // Declaration statement
public void Bar() // Part of a method declaration
{
Console.WriteLine(x); // Expression statement (using an invocation expression)
} // End of the method declaration, but not a declaration statement
} // End of class declaration, but not a declaration statement
要求它們的目的是讓編譯器可以告訴您何時結束語句而不是繼續下一行:
int x = 5;
int y = x // This isn't the end of the statement!
+ 5; // This is...
一種替代方法(例如,VB使用)是有一個行繼續,你想明確地繼續到下一行,即使當前行是一個有效的語句。
正如評論中所指出的, do
語句在這里是一個異常現象。 我沒有看到為什么這不應該是有效的明顯原因:
do { } while (false)
......但事實並非如此。 這可能與plain while
語句需要語句體這一事實有關,例如while (true);
(空語句)或while (true) {}
(塊語句)。 我最接近的是“因為C#規范說do
語句最后需要一個分號......”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.