Mah*_*ari 16 c# c++ scope switch-statement
这个问题让我想起了一个关于转换的一个未解决的问题:
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 ...");
}
Run Code Online (Sandbox Code Playgroud)
为什么emp在'案例2'中被认可?在C++中(如果我没有错)我们可以一起使用多个案例,但在C#中这是不可能的,我们应该case 1以break 结束,所以下面的代码似乎在C++中是正确的而在C#中是错误的:
case 1:
case 2:
SomeMethodUsedByBothStates();
Run Code Online (Sandbox Code Playgroud)
当我们不能有这样的行为时,为什么我们能够宣布进入case 1并看到它case 2?如果从来没有两个案例一起发生那么为什么要在两者中看到这个对象?
Dav*_*men 34
案例不会在c ++或c#中创建范围.在案例中声明的所有变量都与switch语句的范围相同.如果您希望这些变量在某些特定情况下是本地的,则需要使用大括号:
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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
您展示的第二个代码在C#中完全没问题,假设案例2有一个break或return:
case 1:
// no code here...
case 2:
SomeMethodUsedByBothStates();
break;
Run Code Online (Sandbox Code Playgroud)
空案件可以通过.
什么是不容许是有代码的情况下,分支漏网.因此,以下内容无效:
case 1:
SomeMethodUsedOnlyByCase1();
// no break here...
case 2:
SomeMethodUsedByBothStates();
break;
Run Code Online (Sandbox Code Playgroud)
关于范围的问题是另一个问题.基本上,范围是switch语句本身,而不是case-branch.
要使您的示例编译,只需通过添加花括号来给出自己的case-branches范围:
int personType = 1;
switch (personType)
{
case 1:
{
Employee emp = new Employee();
emp.ExperienceInfo();
break;
}
case 2:
{
Employee emp = new Employee();
emp.ManagementInfo();
break;
}
case 3:
{
Student st = new Student();
st.EducationInfo();
break;
}
default:
MessageBox.Show("Not valid ...");
}
Run Code Online (Sandbox Code Playgroud)