C# switch variable initialization: Why does this code NOT cause a compiler error or a runtime error?(C# 开关变量初始化:为什么这段代码不会导致编译器错误或运行时错误?)
问题描述
...
case 1:
string x = "SomeString";
...
break;
case 2:
x = "SomeOtherString";
...
break;
...
关于 C# 中的 switch 语句,我有什么不明白的地方吗?为什么在使用案例 2 时这不会是错误?
此代码有效且不会引发错误.
Is there something that I am not understanding about the switch statement in C#? Why would this not be an error when case 2 is used?
This code works and doesn't throw an error.
推荐答案
你必须小心你如何看待这里的 switch
语句.事实上,没有创建变量范围.不要仅仅因为 case 中的代码缩进就认为它位于子范围内.
You have to be careful how you think about the switch
statement here. There's no creation of variable scopes going on at all, in fact. Don't let the fact that just because the code within cases gets indented that it resides within a child scope.
当一个 switch 块被编译时,case
标签被简单地转换为标签,并在 switch 语句的开头执行适当的 goto
指令,具体取决于切换表达.实际上,您可以手动使用 goto
语句来创建失败"情况(C# 直接支持),如 MSDN 页面 建议.
When a switch block gets compiled, the case
labels are simply converted into labels, and the appropiate goto
instruction is executed at the start of the switch statement depending on the switching expression. Indeed, you can manually use goto
statements to create "fall-through" situations (which C# does directly support), as the MSDN page suggests.
goto case 1;
如果您特别想为 switch
块中的每个案例创建范围,您可以执行以下操作.
If you specifically wanted to create scopes for each case within the switch
block, you could do the following.
...
case 1:
{
string x = "SomeString";
...
break;
}
case 2:
{
string x = "SomeOtherString";
...
break;
}
...
这要求您重新声明变量x
(否则您将收到编译器错误).确定每个(或至少一些)范围的方法在某些情况下可能非常有用,您肯定会不时在代码中看到它.
This requires you to redeclare the variable x
(else you will receive a compiler error). The method of scoping each (or at least some) can be quite useful in certain situations, and you will certainly see it in code from time to time.
这篇关于C# 开关变量初始化:为什么这段代码不会导致编译器错误或运行时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 开关变量初始化:为什么这段代码不会导致编译器错误或运行时错误?


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01