C#switch语句有/无大括号....有什么区别? [英] C# Switch statement with/without curly brackets.... what's the difference?
问题描述
的C#总是允许你省略花括号中的开关
语句? 之间()
语句内部情况:
什么是省略他们的影响,因为JavaScript程序员经常做?
例如:
开关(X)
{
情况下单向:
{//< ----这忽略整行
INT Y = 123;
FindYou(REF Y);
中断;
} //< ----这忽略整行
的情况下换另一支:
{//< ----这忽略整行
双Y = 456.7; //合法的!
GetchaGetcha(REF Y);
中断;
} //< ----这忽略整行
}
花括号不是必需的,但他们可能会派上用场,以引入新的声明空间。这种行为,因为C#,据我所知1.0并没有改变。
忽略它们的效果是所有的变量声明的开关内部的某处
语句是从他们在所有情况下的分支点报关可见
又见埃里克利珀的例子(案例3在后):
块引用>
Eric的例子:
开关(X)
{
情况下单向:
INT Y = 123;
FindYou(REF Y);
中断;
的情况下换另一支:
双Y = 456.7; //非法!
GetchaGetcha(REF Y);
中断;
}
这不会编译,因为
诠释是
和双Y
是由开关
语句引入了相同的声明空间。开关(X)
{
:您可以通过分离用括号括起来的声明空间修复错误案例单向:
{
INT Y = 123;
FindYou(REF Y);
中断;
}
的情况下换另一支:
{
双Y = 456.7; //合法的!
GetchaGetcha(REF Y);
中断;
}
}
Has C# always permitted you to omit curly brackets inside a
switch()
statement between thecase:
statements?What is the effect of omitting them, as javascript programmers often do?
Example:
switch(x) { case OneWay: { // <---- Omit this entire line int y = 123; FindYou(ref y); break; } // <---- Omit this entire line case TheOther: { // <---- Omit this entire line double y = 456.7; // legal! GetchaGetcha(ref y); break; } // <---- Omit this entire line }
解决方案Curly braces are not required, but they might come in handy to introduce a new declaration space. This behavior hasn't changed since C# 1.0 as far as I know.
The effect of omitting them is that all variables declared somewhere inside the
switch
statement are visible from their point of declaration throughout all case branches.See also Eric Lippert's example (case 3 in the post):
Eric's example:
switch(x) { case OneWay: int y = 123; FindYou(ref y); break; case TheOther: double y = 456.7; // illegal! GetchaGetcha(ref y); break; }
This does not compile because
int y
anddouble y
are in the same declaration space introduced by theswitch
statement. You can fix the error by separating the declaration spaces using braces:switch(x) { case OneWay: { int y = 123; FindYou(ref y); break; } case TheOther: { double y = 456.7; // legal! GetchaGetcha(ref y); break; } }
这篇关于C#switch语句有/无大括号....有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!