当多个 Case 做同样的事情时,避免 Switch 语句冗余? [英] Avoid Switch statement redundancy when multiple Cases do the same thing?

查看:50
本文介绍了当多个 Case 做同样的事情时,避免 Switch 语句冗余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

推荐答案

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

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

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

这篇关于当多个 Case 做同样的事情时,避免 Switch 语句冗余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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