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"?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01