在switch语句奇怪的变量范围 [英] odd variable scope in switch statement
问题描述
这个问题让我想起了一个古老的悬而未决的问题在我的脑海约开关:
This question reminded me of an old unanswered question in my mind about switch:
int personType = 1;
switch (personType)
{
case 1:
Employee emp = new Employee();
emp.ExperienceInfo();
break;
case 2:
Employee emp = new Employee();
//Error: A local variable named 'emp' is already defined in this scope
emp.ManagementInfo();
break;
case 3:
Student st = new Student();
st.EducationInfo();
break;
default:
MessageBox.Show("Not valid ...");
}
为什么EMP在案例2的认可?在C ++(如果我没看错),我们可以使用多种情况在一起,但在C#中这是不可能的,我们应该关闭案例1
与休息所以下面的代码似乎是正确的C ++和错误在C#中:
why is emp recognized in 'case 2'? in C++ (if I am not wrong) we could use multiple cases together, but in C# that is impossible and we should close case 1
with break so the following code seems right in C++ and wrong in C#:
case 1:
case 2:
SomeMethodUsedByBothStates();
当我们不能有这样的行为,所以我们为什么要能在<$ C $申报EMP C>案例1 ,看看它在 2的情况下
?如果无法在两个个案,一起发生何必对象均可以看到?
When we can not have such behaviour so why should we be able to declare emp in case 1
and see it in case 2
? If never two cases happen together so why should the object be seen in both?
推荐答案
情况下并不创建在C范围++或C#。所有的情况下内声明的变量都在相同的范围,即switch语句。你需要,如果你想这些变量是本地的一些特定的情况下使用大括号:
Cases do not create scope in c++ or in c#. All of those variables declared inside a case are in the same scope, that of the switch statement. You need to use braces if you want those variables to be local to some specific case:
switch (personType)
{
case 1: {
Employee emp = new Employee();
emp.ExperienceInfo();
break;
}
case 2: {
Employee emp = new Employee();
// No longer an error; now 'emp' is local to this case.
emp.ManagementInfo();
break;
}
case 3: {
Student st = new Student();
st.EducationInfo();
break;
}
...
}
这篇关于在switch语句奇怪的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!