switch 语句中的奇变量范围

odd variable scope in switch statement(switch 语句中的奇变量范围)

本文介绍了switch 语句中的奇变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题让我想起了一个关于switch的老问题:

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# 中这是不可能的,我们应该用 break 关闭 case 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();

当我们不能有这样的行为时,为什么我们应该能够在 case 1 中声明 emp 并在 case 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# 中,Case 不会创建作用域.在 case 中声明的所有这些变量都在相同的范围内,即 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 语句中的奇变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:switch 语句中的奇变量范围

基础教程推荐