C#带/不带花括号的Switch语句。。。。什么';有什么区别?
C#是否总是允许您在C#带/不带花括号的Switch语句。。。。什么';有什么区别?,c#,switch-statement,curly-braces,C#,Switch Statement,Curly Braces,C#是否总是允许您在case:语句之间省略switch()语句中的花括号 就像javascript程序员经常做的那样,省略它们会有什么影响 例如: switch(x) { case OneWay: { // <---- Omit this entire line int y = 123; FindYou(ref y); break; }
case:
语句之间省略switch()
语句中的花括号
就像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
}
int x = 42;
{
int y = x;
}
{
int y = x + 1; // legal, as it's in a separate scope
}
开关(x)
{
案例单向:
{//大括号是的可选部分,它们不是开关部分的一部分。大括号可以插入开关部分中,也可以插入任意位置以控制代码中的范围
它们可用于限制开关块内的范围。例如:
int x = 5;
switch(x)
{
case 4:
int y = 3;
break;
case 5:
y = 4;
//...
break;
}
对
注意:C#将要求您在使用前在第一个示例中的case 5块内将值设置为y。这是防止意外变量跟踪的保护措施。它们不是严格必需的,但一旦您开始声明局部变量(在开关分支中),就非常推荐它们
这行不通:
// does not compile
switch (x)
{
case 1 :
int j = 1;
...
break;
case 3:
int j = 3; // error
...
break;
}
这可以编译,但很可怕:
switch (x)
{
case 1 :
int j = 1;
...
break;
case 3:
j = 3;
...
break;
}
所以这是最好的:
switch (x)
{
case 1 :
{
int j = 1;
...
}
break; // I prefer the break outside of the { }
case 3:
{
int j = 3;
...
}
break;
}
保持简单易读。您不希望读者对中间示例中涉及的规则有详细的了解。
< P>大括号是不需要的,但它们可能会方便地引入新的<强>声明空间< /强>。据我所知,这种行为自C 1以来没有改变。
省略它们的效果是,在switch
语句中声明的所有变量都可以从它们的声明点在所有case分支中看到
另请参见Eric Lippert的示例(文章中的案例3):
Eric的例子:
switch(x)
{
case OneWay:
int y = 123;
FindYou(ref y);
break;
case TheOther:
double y = 456.7; // illegal!
GetchaGetcha(ref y);
break;
}
这不会编译,因为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;
}
}
开关内部的大括号实际上根本不是开关结构的一部分,它们只是作用域块,可以在任何地方的代码中应用
拥有和不拥有它们的区别在于每个块都有自己的作用域。您可以在作用域内声明局部变量,这不会与另一个作用域中的其他变量冲突
例如:
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
}
int x = 42;
{
int y = x;
}
{
int y = x + 1; // legal, as it's in a separate scope
}
+1.特别是当您的交换机内容非常重要时,这非常方便。从java世界来看,“Spooky”是准确的: