switch 语句上的 Java Enum

发布于 2024-12-16 18:30:42 字数 577 浏览 2 评论 0原文

我这里有这段代码,我真的不明白为什么 switch 语句中有一个“this”关键字,看看这段代码

public enum InstrumentType{

    GUITAR,BANJO,MANDOLIN,DOBRO, FIDDLE ,BASS,

    public String toString(){
        switch(this){
        case GUITAR:
            return "Guitar";
        case BANJO: 
            return "Banjo";
        case DOBRO:
            return "Dobro";
        case FIDDLE:
            return "Fiddle";
        case BASS:
            return "Bass";
        case MANDOLIN:
            return "Mandolin";
        default: 
            return "Unspecified";
        }
    }
}

I have this piece of code right here , I really don't get it why is that there is a "this" keyword in the switch statement, take a look at this code

public enum InstrumentType{

    GUITAR,BANJO,MANDOLIN,DOBRO, FIDDLE ,BASS,

    public String toString(){
        switch(this){
        case GUITAR:
            return "Guitar";
        case BANJO: 
            return "Banjo";
        case DOBRO:
            return "Dobro";
        case FIDDLE:
            return "Fiddle";
        case BASS:
            return "Bass";
        case MANDOLIN:
            return "Mandolin";
        default: 
            return "Unspecified";
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

空名 2024-12-23 18:30:42

当前的 InstrumentType

static void MyFunc( )
{
    InstrumentType f = InstrumentType.GUITAR;
    String s = f.toString();
}

这里 this 指的是调用 f.toString() 时 。 这个将具有GUITAR

Here this refers to the current InstrumentType value

static void MyFunc( )
{
    InstrumentType f = InstrumentType.GUITAR;
    String s = f.toString();
}

When f.toString() is invoked. this will have GUITAR value

十年九夏 2024-12-23 18:30:42

它指的是当前实例。

如果你有一个 anum 实例“foo”:

String s = foo.toString();

It refers to the current instance.

If you had an anum instance "foo":

String s = foo.toString();
挽容 2024-12-23 18:30:42

this 指向其容器类/结构体/枚举类元素。在本例中,this 用于 InstrumentType。这是大多数面向对象语言的基本规则。

this points to its container class/struct/enum like elements. in this case, this is used for InstrumentType. it's a basic rule for most of the OO languages.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文