C# 开关变量初始化:为什么这段代码不会导致编译器错误或运行时错误?

C# switch variable initialization: Why does this code NOT cause a compiler error or a runtime error?(C# 开关变量初始化:为什么这段代码不会导致编译器错误或运行时错误?)

本文介绍了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# 开关变量初始化:为什么这段代码不会导致编译器错误或运行时错误?

基础教程推荐