使用一个开关'转到'? [英] Use a 'goto' in a switch?
问题描述
我见过建议编码标准,它读取在switch语句落空
。
I've seen a suggested coding standard that reads Never use goto unless in a switch statement fall-through
.
我不明白。究竟会这个例外情况下的样子,这证明一个转到
?
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 ++中,它会同时运行线,如果变量= 2
。这可能是故意的,但它太容易忘记打破;
在第一种情况下标签的结束。出于这个原因,他们提出了在C#非法。为了模仿通过行为的秋天,你必须明确地使用转到
来表达你的意图:
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;
}
<子>这就是说,有的a少数情况下其中转到
实际上是问题的一个好办法。 千万不要关闭你的大脑,提供永不使用的东西规则。如果是100%没有用,就不会在第一个地方的语言存在。不要使用转到
是指引的;它不是一个法律。
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.
这篇关于使用一个开关'转到'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!