java 当多个 Case 做同样的事情时,避免 Switch 语句冗余?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12965738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:59:51  来源:igfitidea点击:

Avoid Switch statement redundancy when multiple Cases do the same thing?

javasyntaxswitch-statement

提问by Zargontapel

I have multiple cases in a switch that do the same thing, like so: (this is written in Java)

我在一个开关中有多个案例做同样的事情,就像这样:(这是用 Java 编写的)

 case 1:
     aMethod();
     break;
 case 2:
     aMethod();
     break;
 case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;

Is there any way I can combine cases 1, 2 and 3 into one case, since they all call the same method?

有什么办法可以将案例 1、2 和 3 合并为一个案例,因为它们都调用相同的方法?

回答by Ted Hopp

case 1:
case 2:
case 3:
    aMethod();
    break;
case 4:
    anotherMethod();
    break;

This works because when it happens to be case 1 (for instance), it falls through to case 2 (no breakstatement), which then falls through to case 3.

这是有效的,因为当它碰巧是案例 1(例如)时,它会落入案例 2(没有break语句),然后落入案例 3。

回答by Reimeus

Sure, you can allow caseclause sections for 1 & 2 to 'fall through' to clause 3 and then breakout of the switchstatement after that:

当然,您可以允许case1 和 2 的子句部分“落入”到子句 3,然后break退出switch语句:

case 1:
case 2:
case 3:
     aMethod();
     break;
case 4:
     anotherMethod();
     break;

回答by Aravind Yarram

Below is the best you can do

下面是你能做的最好的事情

case 1:
case 2:
case 3:
     aMethod();
     break;
 case 4:
     anotherMethod();
     break;

回答by Gene

It's called the "fall through" pattern:

它被称为“跌倒”模式:

case 1:  // fall through
case 2:  // fall through
case 3: 
   aMethod(); 
   break; 
case 4: 
   anotherMethod(); 
   break;