-1

是否可以让一个枚举常量扩展另一个枚举常量(来自同一个枚举)?

伪代码:

private enum Mode{
  FRIGHTENED, BLINKING extends FRIGHTENED, SCATTER
}

这样,可以在switch-block 中使用 enum-constants,如下所示:

switch (some_mode){
  case FRIGHTENED:
    // This would trigger when the actual "some_mode" is set
    //  to FRIGHTENED or BLINKING
    break;
  case BLINKING:
    // This would only trigger if the actual "some_mode" is set to BLINKING
}

是否有任何模式可以让我这样做,或者我只是完全不在我的脑海中?


我可能需要更清楚地了解switch-statement 中显示的用例:我计划不检查所有可能的值,而只检查“父”值。

if (some_mode == Mode.FRIGHTENED){
  // The behavior in FRIGHTENED and BLINKING mode is the same. The only
  //  difference is the way they are visualized.
}
4

3 回答 3

1

在 Java 中,枚举是无法扩展的,所以如果要整理强相关的枚举,可以使用嵌套的枚举构造。请查看此线程

于 2012-05-29T13:21:16.723 回答
0

有一种痛苦的方式来模拟这一点,但是不,一个枚举常量不可能扩展另一个。

于 2012-05-29T13:22:28.750 回答
0

不,没有办法做到这一点。最接近的选择是

switch (some_mode){
  case BLINKING:
    // This would only trigger if the actual "some_mode" is set to BLINKING
    // no break statement!
  case FRIGHTENED:
    // This would trigger when the actual "some_mode" is set
    //  to FRIGHTENED or BLINKING
}
于 2012-05-29T13:21:24.290 回答