switch 语句上的 Java Enum
我这里有这段代码,我真的不明白为什么 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当前的 InstrumentType 值
这里 this 指的是调用
f.toString()
时 。 这个将具有GUITAR值Here this refers to the current InstrumentType value
When
f.toString()
is invoked. this will have GUITAR value它指的是当前实例。
如果你有一个 anum 实例“foo”:
It refers to the current instance.
If you had an anum instance "foo":
this
指向其容器类/结构体/枚举类元素。在本例中,this
用于InstrumentType
。这是大多数面向对象语言的基本规则。this
points to its container class/struct/enum like elements. in this case,this
is used forInstrumentType
. it's a basic rule for most of the OO languages.