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

查看:115
本文介绍了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.

推荐答案

你必须要小心你如何看待有关开关语句在这里。还有的没有创建变量的作用域的事情在所有,事实上。不要让这只是因为案件中的代码被缩进,它驻留在子范围内的事实。

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语句开始执行。事实上,你可以手动使用转到语句来创建落空的情况(其中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;

如果你特别想为开关内的每一种情况下<创建范围/ 。code>块,你可以做以下

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#开关变量初始化:为什么这个代码不会导致编译器错误或运行时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆