问题描述
为什么C#允许代码块,而不前面的语句(如如果
,其他
,为
,,而
)?
无效的主要()
{
{//在这个任何意义?
Console.Write(富);
}
}
在你给的背景下,就没有意义。写一个常量字符串到控制台会在任何地方以同样的方式在程序流程。
相反,你通常用它们来限制一些局部变量的范围。这这里进一步阐述。看看。我相信同样适用于C风格的语法,一些其他语言,而不是他们会是有关这个问题虽然。
Why does C# allow code blocks without a preceding statement (e.g. if
, else
, for
, while
)?
void Main()
{
{ // any sense in this?
Console.Write("foo");
}
}
In the context you give, there is no significance. Writing a constant string to the console is going to work the same way anywhere in program flow.
Instead, you typically use them to restrict the scope of some local variables. This is further elaborated here and here. Look at João Angelo’s answer and Chris Wallis’s answer for brief examples. I believe the same applies to some other languages with C-style syntax as well, not that they’d be relevant to this question though.
这篇关于为什么C#允许在没有前面的语句{}代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!