Java:在子类下使用带有枚举的switch语句 [英] Java: using switch statement with enum under subclass

查看:142
本文介绍了Java:在子类下使用带有枚举的switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我会说明我对C#中的枚举非常熟悉,而且java中的枚举似乎很麻烦。



正如你所见,我试图在下一个例子中使用一个switch语句@枚举,但总是会收到一个错误,无论我在做什么。



错误我收到的是:


合格案例标签 SomeClass.AnotherClass.MyEnum.VALUE_A 必须被替换为不合格的枚举常量 VALUE_A


事情是我相当了解错误,但是我不能仅仅写入一个VALUE_A,因为枚举位于另一个子类中。有没有办法解决这个问题?为什么会发生在Java中?

  //主类
public class SomeClass {

//子类
public static class AnotherClass {
public enum MyEnum {
VALUE_A,VALUE_B
}
public MyEnum myEnum;
}

public void someMethod(){
MyEnum enumExample // ...

switch(enumExample){
case AnotherClass。 MyEnum.VALUE_A:{< - 此行上的错误
// ..
break;
}
}
}
}


解决方案

将其更改为:

  switch(enumExample){
case VALUE_A: {
// ..
break;
}
}

线索在错误中。您不需要符合案例标签与枚举类型,只是其值。


First I'll state that I'm much more familiar with enums in C# and it seems like enums in java is a quite mess.

As you can see, I'm trying to use a switch statement @ enums in my next example but I always get an error no matter what I'm doing.

The error I receive is:

The qualified case label SomeClass.AnotherClass.MyEnum.VALUE_A must be replaced with the unqualified enum constant VALUE_A

The thing is I quite understand the error but I can't just write the VALUE_A since the enum is located in another sub-class. Is there a way to solve this problem? And why is it happening in Java?

//Main Class
public class SomeClass {

    //Sub-Class
    public static class AnotherClass {
        public enum MyEnum {
            VALUE_A, VALUE_B
        }    
        public MyEnum myEnum;
    }

    public void someMethod() { 
        MyEnum enumExample //...

        switch (enumExample) {
            case AnotherClass.MyEnum.VALUE_A: { <-- error on this line
                //..
                break;
            }
        }
    }
}

解决方案

Change it to this:

switch (enumExample) {
    case VALUE_A: {
        //..
        break;
    }
}

The clue is in the error. You don't need to qualify case labels with the enum type, just its value.

这篇关于Java:在子类下使用带有枚举的switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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