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"?
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
