Java:在子类下使用带有枚举的switch语句 [英] Java: using switch statement with enum under subclass
问题描述
正如你所见,我试图在下一个例子中使用一个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 constantVALUE_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屋!