goo*_*ate 69 c# curly-braces switch-statement
C#总是允许你在switch()
语句之间的case:
语句中省略大括号吗?
如javascript程序员经常做的那样省略它们有什么作用?
例:
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
}
Run Code Online (Sandbox Code Playgroud)
Dir*_*mar 103
不需要卷曲括号,但它们可能会派上用场来引入新的声明空间.据我所知,自C#1.0以来,这种行为没有改变.
省略它们的效果是在switch
声明中声明的所有变量在所有case分支的声明点都是可见的.
另请参阅Eric Lippert的示例(帖子中的案例3):
埃里克的例子:
switch(x)
{
case OneWay:
int y = 123;
FindYou(ref y);
break;
case TheOther:
double y = 456.7; // illegal!
GetchaGetcha(ref y);
break;
}
Run Code Online (Sandbox Code Playgroud)
这不会编译因为int y
并且double y
在switch
语句引入的同一声明空间中.您可以通过使用大括号分隔声明空间来修复错误:
switch(x)
{
case OneWay:
{
int y = 123;
FindYou(ref y);
break;
}
case TheOther:
{
double y = 456.7; // legal!
GetchaGetcha(ref y);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*ndy 14
花括号是开关块的可选部分,它们不是开关部分的一部分.大括号可以插入开关部分或同等插入任何位置以控制代码中的范围.
它们可用于限制开关块内的范围.例如:
int x = 5;
switch(x)
{
case 4:
int y = 3;
break;
case 5:
y = 4;
//...
break;
}
Run Code Online (Sandbox Code Playgroud)
VS ...
int x = 5;
switch(x)
{
case 4:
{
int y = 3;
break;
}
case 5:
{
y = 4;//compiling error
//...
break;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:在使用之前,C#将要求您在第一个示例中的case 5块中将值设置为y.这是对意外变量的保护.
开关内的支架实际上根本不是开关结构的一部分.它们只是范围块,您可以在任何您喜欢的代码中应用它们.
拥有它们和没有它们之间的区别在于每个块都有它自己的范围.您可以在范围内声明局部变量,这不会与另一个范围中的其他变量冲突.
例:
int x = 42;
{
int y = x;
}
{
int y = x + 1; // legal, as it's in a separate scope
}
Run Code Online (Sandbox Code Playgroud)
它们不是绝对必要的,但是一旦您开始声明局部变量(在 switch 分支中),就非常推荐使用它们。
这行不通:
// does not compile
switch (x)
{
case 1 :
int j = 1;
...
break;
case 3:
int j = 3; // error
...
break;
}
Run Code Online (Sandbox Code Playgroud)
这编译但它是怪异的:
switch (x)
{
case 1 :
int j = 1;
...
break;
case 3:
j = 3;
...
break;
}
Run Code Online (Sandbox Code Playgroud)
所以这是最好的:
switch (x)
{
case 1 :
{
int j = 1;
...
}
break; // I prefer the break outside of the { }
case 3:
{
int j = 3;
...
}
break;
}
Run Code Online (Sandbox Code Playgroud)
只要保持简单和可读。您不想要求读者详细了解中间示例中涉及的规则。