Why do I need to use break?(为什么我需要使用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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我需要使用break?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01