为什么我在 case 标签中得到一个 Enum 常量引用不能被限定? [英] Why do I get an Enum constant reference cannot be qualified in a case label?

查看:14
本文介绍了为什么我在 case 标签中得到一个 Enum 常量引用不能被限定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码编译失败,同时把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();
        }
    }
}

推荐答案

这是为了避免与不同的枚举类型进行比较的能力.将其限制为 one 类型是有意义的,即 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 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 上使用常量,并且没有两个这样的常量值可能相同.编译器在编译时检查 switch 语句中的重复常量值;class 文件格式不会对 case 值进行符号链接.

One reason for requiring inlining of constants is that switch statements require constants on each case, and no two such constant values may be the same. The compiler checks for duplicate constant values in a switch statement at compile time; the class file format does not do symbolic linkage of case values.

换句话说,由于EnumType.ENUM1中的类标识符,它不能表示为编译时常量表达式,而switch语句需要它.

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.

这篇关于为什么我在 case 标签中得到一个 Enum 常量引用不能被限定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆