C# Switch statement with/without curly brackets.... what#39;s the difference?(带/不带大括号的 C# Switch 语句....有什么区别?)
问题描述
Has C# always permitted you to omit curly brackets inside a switch()
statement between the case:
statements?
What is the effect of omitting them, as javascript programmers often do?
Example:
switch(x)
{
case OneWay:
{ // <---- Omit this entire line
int y = 123;
FindYou(ref y);
break;
} // <---- Omit this entire line
case TheOther:
{ // <---- Omit this entire line
double y = 456.7; // legal!
GetchaGetcha(ref y);
break;
} // <---- Omit this entire line
}
Curly braces are not required, but they might come in handy to introduce a new declaration space. This behavior hasn't changed since C# 1.0 as far as I know.
The effect of omitting them is that all variables declared somewhere inside the switch
statement are visible from their point of declaration throughout all case branches.
See also Eric Lippert's example (case 3 in the post):
Four switch oddities
Eric's example:
switch(x)
{
case OneWay:
int y = 123;
FindYou(ref y);
break;
case TheOther:
double y = 456.7; // illegal!
GetchaGetcha(ref y);
break;
}
This does not compile because int y
and double y
are in the same declaration space introduced by the switch
statement. You can fix the error by separating the declaration spaces using braces:
switch(x)
{
case OneWay:
{
int y = 123;
FindYou(ref y);
break;
}
case TheOther:
{
double y = 456.7; // legal!
GetchaGetcha(ref y);
break;
}
}
这篇关于带/不带大括号的 C# Switch 语句....有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带/不带大括号的 C# Switch 语句....有什么区别?
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01