【发布时间】:2012-11-23 08:10:41
【问题描述】:
This question 让我想起了一个关于 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# 中这是不可能的,我们应该用 break 关闭 case 1,所以下面的代码在 C++ 中似乎是正确的,而在 C# 中是错误的:
case 1:
case 2:
SomeMethodUsedByBothStates();
当我们不能有这样的行为时,为什么我们应该能够在case 1 中声明 emp 并在case 2 中看到它?如果从来没有两种情况同时发生,那为什么要同时看到对象呢?
【问题讨论】:
标签: c# c++ scope switch-statement