为什么C#允许在没有前面的语句{}代码块? [英] Why does C# allow {} code blocks without a preceding statement?

查看:116
本文介绍了为什么C#允许在没有前面的语句{}代码块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C#允许代码块,而不前面的语句(如如果其他,而)?

 无效的主要()
{
{//在这个任何意义?
Console.Write(富);
}
}


解决方案

在你给的背景下,就没有意义。写一个常量字符串到控制台会在任何地方以同样的方式在程序流程。 1



相反,你通常用它们来限制一些局部变量的范围。这这里进一步阐述和的此处。看看若昂Angelo的答案克里斯·沃利斯对简短的例子回答。我相信同样适用于C风格的语法,一些其他语言,而不是他们会是有关这个问题虽然。<​​/ p>




1 除非,当然,你决定尝试是滑稽和创建自己的控制台类,具有写()方法,做事情完全出乎意料。


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.1

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.


1 Unless, of course, you decide to try to be funny and create your own Console class, with a Write() method that does something entirely unexpected.

这篇关于为什么C#允许在没有前面的语句{}代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆