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 中多余的大括号的作用是什么?
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
