What is the purpose of the extra braces in Switch case?(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 中多余的大括号的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Switch case 中多余的大括号的作用是什么?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01