在开关内使用枚举
我们可以在开关内使用枚举吗?
public enum Color {
RED,BLUE,YELLOW
}
public class Use {
Color c = Color.BLUE;
public void test(){
switch(c){
case Color.BLUE:
}
}
}
我在这方面遇到一些错误。
The enum constant Color.BLUE reference cannot be qualified in a case label Use.java line 7 Java Problem
Can we use enum inside a switch?
public enum Color {
RED,BLUE,YELLOW
}
public class Use {
Color c = Color.BLUE;
public void test(){
switch(c){
case Color.BLUE:
}
}
}
I am getting some error in this.
The enum constant Color.BLUE reference cannot be qualified in a case label Use.java line 7 Java Problem
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在上面的代码中,只写 BLUE
E.G,而不是 COLOR.BLUE。
In the above code instead of COLOR.BLUE only write BLUE
E.G.
像这样写:
enum
标签用作 case 标签时不得进行限定。 JLS 14.11 的语法是这样说的:需要一个简单的标识符,而不是由枚举名称限定的标识符。
(我不知道他们为什么这样设计语法。可能是为了避免语法中的一些歧义。但无论如何,事情就是这样。)
Write it like this:
The
enum
label MUST NOT be qualified when used as a case label. The grammar at JLS 14.11 says this:Note that a simple identifier is require, not an identifier qualified by the enum name.
(I don't know why they designed the syntax like that. Possibility it was to avoid some ambiguity in the grammar. But either way, that's the way it is.)
为什么要使用开关?而是让枚举本身保存颜色信息(封装它),从而完成所有脏工作。这样做的优点是,如果您更改枚举,则不必遍历所有使用它的代码,更改所有 switch 语句。例如:
如何使用它的示例如下:
Why use a switch at all? Rather just let the enum hold the Color information itself (encapsulate it) and thereby do all the dirty work. The advantage to this, is if you change your enum, you don't have to root through all code that uses it, changing all switch statements. For instance:
and an example of how this can be used is as follows:
是的,您可以在 switch 语句中使用枚举,但请确保不要在 case 标签中使用 FQCN(完全限定类名)。
以下内容摘自“枚举常量引用无法限定”在 switch 语句的 case 标签中”
简而言之
当 Java switch 语句使用 enum 参数时;枚举值的限定名称不应在 case 标签中使用,而只能使用非限定名称;那么 switch 语句将认为所有标签都引用用作参数的枚举类型。
为什么只有不合格的值?
如果案例标签允许合格的参考;无法限制标签中使用的枚举类型与 switch 语句的参数类型相同。
Yes, you can use enums in switch statements, but make sure not to use FQCN (fully-Qualified Class Name) in case labels.
Following is extracted from "enum constant reference cannot be qualified in a case label of switch statement"
In Short
When a Java switch statement uses an enum parameter; qualified names of the enum values should not be used in case labels, but only the unqualified names; then switch statement will consider all the labels are referring to the enum type that is used as the parameter.
Why only unqualified values?
If qualified references were allowed for case labels; there would be no means to restrict the enum type used in the labels to be same as the parameter type of switch statement.