9
...
case 1:
   string x = "SomeString";
   ...
   break;
case 2:
   x = "SomeOtherString";
   ...
   break;
...


Is there something that I am not understanding about the switch statement in C#? Why would this not be an error when case 2 is used?
Edit: This code works and doesn't throw an error.

4

6 回答 6

18

你必须小心你如何看待switch这里的陈述。事实上,根本没有创建变量范围。不要仅仅因为 case 中的代码缩进就认为它位于子范围内。

当一个 switch 块被编译时,case标签被简单地转换为标签,并goto根据 switch 表达式在 switch 语句的开头执行适当的指令。实际上,正如MSDN 页面所建议的那样,您可以手动使用goto语句来创建“失败”情况(C# 直接支持) 。

goto case 1;

如果您特别想为块中的每个案例创建范围switch,您可以执行以下操作。

...
case 1:
{
   string x = "SomeString";
   ...
   break;
}
case 2:
{
   string x = "SomeOtherString";
   ...
   break;
}
...

需要您重新声明变量x(否则您将收到编译器错误)。确定每个(或至少一些)范围的方法在某些情况下可能非常有用,您肯定会不时在代码中看到它。

于 2009-05-14T15:55:49.680 回答
8

The documentation on MSDN says :

The scope of a local variable declared in a switch-block of a switch statement (Section 8.7.2) is the switch-block.

Also, a similar question has been asked before: Variable declaration in c# switch statement

于 2009-05-14T15:55:07.997 回答
4

没有编译器错误,因为 switch 语句没有为变量创建新的范围。

如果您在开关内声明变量,则该变量与开关周围的代码块在同一范围内。要更改此行为,您需要添加 {}:

...
case 1:
    // Start a new variable scope 
    {
        string x = "SomeString";
        ...
    }
    break;
case 2:
    {
        x = "SomeOtherString";
        ...
    }
    break;
...

这将导致编译器抱怨。但是, switch 本身并不在内部执行此操作,因此您的代码中没有错误。

于 2009-05-14T15:56:38.787 回答
1

看起来变量的范围是在 switch 中,而不是 case,可能是因为 case 可以堆叠。请注意,如果您尝试在交换机之外引用 x ,它将失败。

于 2009-05-14T15:59:32.370 回答
0

如果在 case 中创建任何局部变量,则不能在 case 之外使用它们。

...
int opt ;
switch(opt)
{
case 1:
{
   string x = "SomeString";
   ...
}
   break;
case 2:
{
   string x = "SomeOtherString";
   ...
}
   break;
default:
{
//your code
}
break;
}
...
于 2009-05-14T15:56:17.430 回答
-2

move the string declaration to before the

switch(value)

statement. Then assign x for each case.

于 2009-05-14T15:52:59.500 回答