可能重复:
C# switch variable initialization: Why does this code NOT cause a compiler error or a runtime error?
在这个switch语句中(我惊讶地编译并执行而没有错误),在case 2中没有声明变量,而case 1从不执行。这有效吗?如何在不声明的情况下使用变量?
switch(2){
case 1:
string something = "whatever";
break;
case 2:
something = "where??";
break;
}
答案 0 :(得分:5)
这是因为switch
语句的范围跨越了案例。因此,当最初处理switch
语句时,它定义了一个名为something
的变量,并且具有默认值...在这种情况下为null
。
更准确地说,当生成IL时,在其定义或低于其定义的任何case
范围内,变量可用。因此,如果变量在第二个case
中声明,则在第一个case
中不可用,但在第三个case
中可用。