我只是想弄清楚为什么在下面的一些行不以分号结束但其他行做的技术原因 - 它是什么关于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**
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 55
分号不是行终止符......它是一个语句终止符.每个表达式语句和声明语句的末尾都有一个分号.
(if,for等陈述不是表达或声明陈述.)
例如:
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
Run Code Online (Sandbox Code Playgroud)
要求它们的目的是让编译器可以告诉您何时结束语句而不是继续下一行:
int x = 5;
int y = x // This isn't the end of the statement!
+ 5; // This is...
Run Code Online (Sandbox Code Playgroud)
一种替代方法(例如,VB使用)是有一个行继续,你想明确地继续到下一行,即使当前行是一个有效的语句.
正如评论中所指出的,do声明在这里是一个异常现象.我没有看到为什么这不应该是有效的明显原因:
do { } while (false)
Run Code Online (Sandbox Code Playgroud)
......但事实并非如此.这可能与plain while语句需要语句体(例如while (true);(空语句)或while (true) {}(块语句))的事实有关.我最接近的是"因为C#规范说do声明最后需要一个分号......"
| 归档时间: |
|
| 查看次数: |
3983 次 |
| 最近记录: |