为什么我需要使用break? [英] Why do I need to use break?

查看:31
本文介绍了为什么我需要使用break?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么 C# 要求我在 switch 语句中使用 break,尽管根据定义不允许贯穿语义.因此,编译器可以在每个 case 块的末尾生成 break 并为我省去麻烦.

I was wondering why C# requires me to use break in a switch statement although a fall-through semantics is by definition not allowed. hence, the compiler could generate the break at the end of each case-block and save me the hassle.

但是,我可以提出一种情况(已在本网站上讨论过),这可能是显式使用 break 的原因:

However, there is one scenario (which has already been discussed on this site) which I could come up with that might be the reason for the explicit usage of break:

switch (foo) {
    case 0:
    case 1:
        bar();
        break;
    default:
        break;
}

这里,如果 foo 的值为 0 或 1,则调用方法 bar().

Here, the method bar() is called if foo has either the value 0 or 1.

如果编译器会自行生成 break 语句,则此选项将真正意义上的中断.是这样吗,这是强制休息的原因还是有其他好的理由?

This option would break in the truest sense of the word if the compiler would generate break statements by itself. Is this it, is this the reason why the break is compulsory or are there any other good reasons?

推荐答案

我怀疑 C# 要求开发人员在每个案例的末尾放置一个 break 或 terminal 语句的原因是为了清楚起见.

它避免了该语言的新手假设 C# 中的 switch( ) 的行为类似于 C 或 C++ 中的 switch,其中会发生失败行为.只有在相邻的空case的情况下才会在C#中出现fallthrough——这是比较明显的.

It avoids newcomers to the language from assuming that switch( ) in C# behaves like switch in C or C++ where fall through behavior occurs. Only in the cases of adjacent empty cases does fall through occur in C# - which is relatively obvious.

实际上,在 C# 中,失败总是非法的.然而,合法的是有一个案例与两个或多个标签相关联.Eric Lippert 详细描述了这种行为以及如何它不同于 C/C++ 的 switch 语句.

Actually, in C# fallthrough is always illegal. What is legal, however, is having a single case associated with two or more labels. Eric Lippert writes at length about this behavior and how it differs from C/C++ switch statements.

您可能有兴趣阅读 此Eric Lipperts 博客上的文章.

这篇关于为什么我需要使用break?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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