为什么C#有突破,如果它不是可有可无的? [英] Why does C# have break if it's not optional?

查看:189
本文介绍了为什么C#有突破,如果它不是可有可无的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在VS2008 C#创建一个开关语句是这样的(人为):

When I create a switch statement in VS2008 C# like this (contrived):

switch (state) {
    case '1':
        state = '2';
    case '2':
        state = '1';
}



它抱怨说,我不能放弃通过:

it complains that I'm not allowed to drop through:

Control无法通过从一个case标签回落('情况'1'(0X31):')到另一个

Control cannot fall through from one case label ('case '1' (0x31):') to another

如果你不允许通过掉落,那么什么是语句在所有的目的是什么?为什么没有语言的设计者刚刚离开出来,并自动跳转到开关语句的结束,而不是强迫我们把在不必要的构造?

If you're not allowed to drop through, then what is the purpose of the break statement at all? Why didn't the language designers just leave it out and automatically jump to the end of the switch statement instead of forcing us to put in an unnecessary construct?

推荐答案

从马的嘴(MSDN)的Why是C#switch语句设计不允许落空,但仍需要休息?

From the horse's mouth (MSDN) Why is the C# switch statement designed to not allow fall-through, but still require a break?.

引用的突出位,这就是为什么他们不允许落空:

Quoting the salient bits, this is why they don't allow fall-through:

这隐含的下降沿继续通过行为经常用来减少所需的代码量,往往不是一个问题的第一时间代码被写入。然而,随着代码的最初开发阶段移动到维护阶段,上面的代码可以导致一些很难调试细微的错误。这些错误从开发商增加的情况下,还不忘把休息的块结束的非常常见的错误造成的。

This implicit fall-through behavior is often used to reduce the amount of code needed and often isn't an issue the first time that code is written. However, as code moves from the initial development phase into a maintenance phase, the code above can lead to subtle errors that are very hard to debug. These errors result from the very common mistake of the developer adding a case, yet forgetting to put a break at the end of the block.

在C#中,switch语句要求显式流量控制出现在案件结束后,无论是休息,跳转,返回,或者抛出。如果开发商希望落空语义,它可以通过在case语句的最后一个明确的goto来实现。

In C#, the switch statement requires that explicit flow control occur at the end of a case, either a break, goto, return, or throw. If the developer desires fall-through semantics, it can be achieved by an explicit goto at the end of a case statement.

和本就是为什么它不是自动的:

And this is why it's not automatic:

由于需要显式流量控制在一个case块结束时发生的C#规则的结果(最通常休息),许多人质疑为什么行为根本没有改变,这样没有发生落空。也就是说,不要让需要休息,简单地改变开关的语义没有落空的情况下。没有这样做的原因是,这样谁是很习惯C ++开发人员不会有一个很难理解什么是switch语句在做什么。

As a result of the C# rules requiring explicit flow-control to occur at the end of a case block (most usually a break), many people question why the behavior simply wasn't changed such that fall-through didn't occur. That is, don't make break required, simply change the semantics of switch to not have fall-through for cases. The reason this wasn't done was so that developers who were very used to C++ wouldn't have a hard time understanding what a switch statement was doing.

这篇关于为什么C#有突破,如果它不是可有可无的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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