C#开关/案例共享相同的作用域? [英] C# Switch/case share the same scope?
问题描述
可能重复:
c#switch语句中的变量声明
我一直想知道:
我写的时候:
switch (temp)
{
case "1":
int tmpInt = 1;
break;
}
情况 1:
地区有一个执行代码的区域(直到中断)
the case "1":
region has a region of code which is executed ( until break)
现在,
无法从上方的瀑布进入 2的情况下
,例如:
a waterfall from above can't get into a case of 2
e.g. :
switch (temp)
{
case "1":
int tmpInt = 1;
case "2":
break;
}
//错误:缺少中断返回。
所以我认为,他们有不同的执行区域(案例.... break)。
So i assume , they have different regions of executions ( case....break).
所以为什么会出现此错误?
so why this errors appears ?
//冲突变量tmpInt定义如下。
ps这只是一个愚蠢的问题,仍然很有趣。
推荐答案
在C#中,作用域仅由花括号确定。如果没有,则没有单独的范围。对于开关
/ 情况
,显然没有。您所谓的执行区域与可以引用变量的位置完全无关。例如:
In C# the scope is determined solely by braces. If there are none, there is no separate scope. With switch
/case
there is obviously none. What you call »region of execution« has nothing to do at all with where you can refer to a variable. For a contrived example:
int x = 1;
goto foo;
// This part gets never executed but you can legally refer to x here.
foo:
不过,您可以执行以下操作:
You can do the following, though, if you like:
switch (temp)
{
case "1":
{
int tmpint = 1;
break;
}
case "2":
{
int tmpint = 1;
break;
}
}
实际上,对于某些切换
语句,是因为它不会污染其他情况
,从而使生活变得更加轻松。我有时会想念Pascal;-)
In fact, for some switch
statements I do that, because it makes life much easier by not polluting other case
s. I miss Pascal sometimes ;-)
关于您尝试的失败,您必须在C#中使用 goto情况 2将其明确显示。
Regarding your attempted fallthrough, you have to make that explicit in C# with goto case "2"
.
这篇关于C#开关/案例共享相同的作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!