Java:在子类下使用带有enum的switch语句
首先,我要说的是,我对C#中的枚举更为熟悉,而java中的枚举似乎相当混乱
如您所见,在下一个示例中,我尝试使用switch语句@enums,但无论我做什么,我总是会遇到错误
我收到的错误是:
The qualified case label
SomeClass.AnotherClass.MyEnum.VALUE_A
must be replaced with the unqualified enum constantVALUE_A
问题是我非常理解这个错误,但是我不能只写值,因为枚举位于另一个子类中。有没有办法解决这个问题?为什么它会发生在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;
}
}
}
}
# 1 楼答案
Java自动推断
case
中元素的类型,因此标签必须是非限定的# 2 楼答案
这就是我使用它的方式。而且它工作得非常好-
和
switch-case
如下所示# 3 楼答案
将其更改为:
线索在错误中。您不需要使用枚举类型限定
case
标签,只需限定其值即可# 4 楼答案
从Java14开始,可以使用开关表达式
这个职位
开关表达式
示例1:返回值
示例2:不返回值
参考文献
Switch Expressions
# 5 楼答案
错:
对:
# 6 楼答案
这应该做到: