如果 C# 不是可选的,为什么会有中断?

Why does C# have break if it#39;s not optional?(如果 C# 不是可选的,为什么会有中断?)

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

问题描述

当我在 VS2008 C# 中创建 switch 语句时,像这样(人为):

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

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

它抱怨我不允许通过:

控件不能从一个 case 标签 ('case '1' (0x31):') 转移到另一个

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

如果你不被允许通过,那么 break 语句的目的到底是什么?为什么语言设计者不直接把它去掉,自动跳转到 switch 语句的末尾,而不是强迫我们放入一个不必要的结构?

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)为什么 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 结束时进行显式流控制,无论是 break、goto、return 还是 throw.如果开发人员需要贯穿语义,可以通过在 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:

由于 C# 规则要求在 case 块的末尾(最常见的是中断)发生显式流控制,许多人质疑为什么行为根本没有改变,以至于失败没有发生.也就是说,不需要 break ,只需将 switch 的语义更改为没有 case 的 fall-through 即可.没有这样做的原因是,非常习惯 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# 不是可选的,为什么会有中断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果 C# 不是可选的,为什么会有中断?

基础教程推荐