为什么我得到一个枚举常数引用不能合格的案例标签? [英] Why do I get an Enum constant reference cannot be qualified in a case label?
问题描述
为什么将case语句更改为
Why does the following code fail to compile, while changing the case statement to
case ENUM1: doSomeStuff();
工作?
public enum EnumType
{
ENUM1, ENUM2, ENUM3;
void doSomeStuff()
{
switch(this)
{
case EnumType.ENUM1: doSomeStuff();
}
}
}
推荐答案
这是为了避免与不同的枚举类型进行比较的能力。将它限制为一个类型,即 开关
语句中枚举值的类型是有意义的。
This is to avoid the ability to compare against different enum types. It makes sense to restrict it to one type, i.e. the type of the enum value in the switch
statement.
更新:它实际上是保持二进制兼容性。以下是第13.4.9节的JLS:
Update: it's actually to keep binary compatibility. Here's a cite from about halfway chapter 13.4.9 of JLS:
需要内联常量的一个原因是
switch
语句需要每个case
上的常量,并且没有两个这样的常量值可能相同。编译器在编译时检查开关
语句中的重复常量值;类
文件格式不符合案例值的连接。
One reason for requiring inlining of constants is that
switch
statements require constants on eachcase
, and no two such constant values may be the same. The compiler checks for duplicate constant values in aswitch
statement at compile time; theclass
file format does not do symbolic linkage of case values.
换句话说,由于 EnumType.ENUM1
中的类标识符,它不能被表示为compiletime常量表达式,而开关
语句。
In other words, because of the class identifier in EnumType.ENUM1
, it cannot be represented as a compiletime constant expression, while it is required by the switch
statement.
这篇关于为什么我得到一个枚举常数引用不能合格的案例标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!