使用一个开关'转到'? [英] Use a 'goto' in a switch?

查看:174
本文介绍了使用一个开关'转到'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过建议编码标准,它读取在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆