什么是开关的情况下额外的括号的目的是什么? [英] What is the purpose of the extra braces in Switch case?

查看:117
本文介绍了什么是开关的情况下额外的括号的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇这件事......看到例如:

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

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



我所有的生活中,我已经做了类似的情况下B,但由于C#允许我使用它,和Visual Studio可以让我崩溃的事情,我很好奇 - 是什么情况下(用大括号)和案例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++;
    }
}



正如你所看到的,在那一个方法,我已经创建四个变量,每个称为一个。因为,作为局部变量,它们只属于自己的范围内,存在于每个是完全独立的。

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.

这是否使某种意义?

这篇关于什么是开关的情况下额外的括号的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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