这个问题让我想起了我心中一个有关 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 ...");
}
为什么在'case 2'中会识别emp?在C++中(如果我没记错的话)我们可以一起使用多个cases,但在C#中这是不可能的,我们需要使用break来关闭case 1
,所以在C++中以下代码看起来是正确的而在C#中则是错误的:
case 1:
case 2:
SomeMethodUsedByBothStates();
如果我们不能在case 1
中声明并在case 2
中看到emp,那么为什么应该允许这样的行为?如果永远不会同时发生两种情况,那么为什么对象应该在两种情况下都可见?