Switch case 中多余的大括号的作用是什么? [英] What is the purpose of the extra braces in Switch case?

查看:32
本文介绍了Switch case 中多余的大括号的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这件事很好奇...参见示例:

I'm curious about this thing... see example:

switch(x)
{
    case(a):
        {
        //do stuff
        }
        break;
    case(b):
        //do stuff
        break;
}

我一生都像案例 b 那样做,但是由于 C# 允许我使用它,而 Visual Studio 允许我折叠那个东西,我很好奇 - 案例 a(带大括号)之间的真正区别是什么和案例b?

All my life I've done it like case b, but since C# allows me to use it, and Visual Studio allows me to collapse that thing, I am curious - what is the real difference between case a (with braces) and case b?

推荐答案

大括号 {} 用于定义一组操作的范围.奇怪的是,以下将编译和工作:

Braces {} are used to define a scope for a set of operations. Bizarrely, the following will compile and work:

private void ConnectionStateChange(object sender, StateChangeEventArgs e)
{
    string s = "hi";
    switch(s)
    {
        case "hi":
            {
                int a = 1;
                a++;
            }
            {
                int a = 2;
                a++;
            }
            break;
    }

    {
        int a = 1;
        a++;
    }
    {
        int a = 2;
        a++;
    }
}

如您所见,在该方法中,我创建了四个变量,每个变量称为 a.每个都是完全独立的,因为作为局部变量,它们只存在于自己的范围内.

As you can see, in that one method I've created four variables, each called a. Each is entirely separate because, as local variables, they exist only within their own scope.

这有意义吗?

这篇关于Switch case 中多余的大括号的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆