为什么我得到 Enum 常量引用无法在 case 标签中限定?
为什么下面的代码无法编译,而更改 case 语句却可以
case ENUM1: doSomeStuff();
运行?
public enum EnumType
{
ENUM1, ENUM2, ENUM3;
void doSomeStuff()
{
switch(this)
{
case EnumType.ENUM1: doSomeStuff();
}
}
}
Why does the following code fail to compile, while changing the case statement to
case ENUM1: doSomeStuff();
works?
public enum EnumType
{
ENUM1, ENUM2, ENUM3;
void doSomeStuff()
{
switch(this)
{
case EnumType.ENUM1: doSomeStuff();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是为了避免与不同枚举类型进行比较。将其限制为 one 类型是有意义的,即switch
语句中枚举值的类型。更新:它是实际上是为了保持二进制兼容性。这是大约一半的引用 第 13.4.9 章< JLS 的/a>:
换句话说,由于
EnumType.ENUM1
中的类标识符,它不能表示为编译时常量表达式,而switch
语句需要它。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 theswitch
statement.Update: it's actually to keep binary compatibility. Here's a cite from about halfway chapter 13.4.9 of JLS:
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 theswitch
statement.这并没有真正回答您的问题,但如果您有取决于枚举值的代码,您还可以在枚举中创建一个抽象方法,该方法会为每个值重载:
This is not really answering your question but if you have code depending on the enum value, you can also create an abstract method in your enum that gets overloaded for every value:
由于您要打开
EnumType
类型的对象,并且它唯一可能的值是枚举常量,因此无需在开关内再次限定这些常量。毕竟,无论如何,其中包含case OtherEnumType.ENUM1:
都是非法的。Since you're switching on an object of type
EnumType
and the only possible values for it are the enum constants, there's no need to qualify those constants again in within the switch. After all, it would be illegal to havecase OtherEnumType.ENUM1:
in it anyway.