Use a #39;goto#39; in a switch?(在开关中使用“goto?)
问题描述
我看到了一个建议的编码标准,它是 Never use goto unless in a switch statement fall-through
.
I've seen a suggested coding standard that reads Never use goto unless in a switch statement fall-through
.
我不关注.这个异常"案例究竟是什么样的,可以证明 goto
的合理性?
I don't follow. What exactly would this 'exception' case look like, that justifies a goto
?
推荐答案
这个构造在 C# 中是非法的:
This construct is illegal in C#:
switch (variable) {
case 2:
Console.WriteLine("variable is >= 2");
case 1:
Console.WriteLine("variable is >= 1");
}
在 C++ 中,如果 variable = 2
,它将运行两行.这可能是故意的,但很容易忘记第一个 case 标签末尾的 break;
.出于这个原因,他们在 C# 中将其设为非法.要模仿跌倒行为,您必须明确使用 goto
来表达您的意图:
In C++, it would run both lines if variable = 2
. It may be intentional but it's too easy to forget break;
at the end of the first case label. For this reason, they have made it illegal in C#. To mimic the fall through behavior, you will have to explicitly use goto
to express your intention:
switch (variable) {
case 2:
Console.WriteLine("variable is >= 2");
goto case 1;
case 1:
Console.WriteLine("variable is >= 1");
break;
}
也就是说,有 少数情况 goto
实际上是很好的解决问题.永远不要关闭你的大脑永远不要使用某些东西"规则.如果它是 100% 无用的,那么它一开始就不会存在于语言中.不要使用 goto
是一个指南;这不是法律.
That said, there are a few cases where goto
is actually a good solution for the problem. Never shut down your brain with "never use something" rules. If it were 100% useless, it wouldn't have existed in the language in the first place. Don't use goto
is a guideline; it's not a law.
这篇关于在开关中使用“goto"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在开关中使用“goto"?


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01