[英]Using an enum instead of a switch case in Gosu
I want to avoid creating a switch case and instead use an enum
but when writing the following code, I get a compile error saying unexpected token public
: 我想避免创建切换用例,而是使用
enum
但是在编写以下代码时,出现编译错误,提示unexpected token public
:
public enum Status {
INACTIVE {
public void doSomething() {
//do something
}
},
ACTIVE {
public void doSomething() {
//do something else
}
},
UNKNOWN {
public void doSomething() {
//do something totally different
}
};
public abstract void doSomething()
}
Basically what I want to achieve is something similar to this: 基本上,我要实现的目标与此类似:
public enum Status {
ACTIVE,
INACTIVE,
UNKNOWN;
}
switch (getState()) {
case INACTIVE:
//do something
break;
case ACTIVE:
//do something else
break;
case UNKNOWN:
//do something totally different
break;
}
Is this allowed in Gosu? Gosu允许这样做吗? How should I go about achieving such a behavior?
我应该如何实现这种行为?
You have miss-understood the concept of Enum
. 您已经误解了
Enum
的概念。 First of all, enum
is inherited from java.lang.Enum
. 首先,
enum
继承自java.lang.Enum
。 It's not allowed to implement inner classes to Enum constants
. 不允许将内部类实现为
Enum constants
。 You have to consider ACTIVE,INACTIVE and UNKNOWN ( Enum constants
) as objects
of class type
Status. 您必须将ACTIVE,INACTIVE和UNKNOWN(
Enum constants
)视为class type
Status的objects
。
Proof: 证明:
Status.ACTIVE.getClass()
== class Status
Status.ACTIVE.getClass()
== class Status
Status.ACTIVE instanceof Status
== true
Status.ACTIVE instanceof Status
== true
Status.ACTIVE instanceof java.lang.Enum
== true
Status.ACTIVE instanceof java.lang.Enum
== true
If you want to avoid the switch
statement in your main code, you can move the switch
into the implementation of enum
as follows; 如果要避免在主代码中使用
switch
语句,可以按如下所示将switch
移到enum
的实现中; (coded in Gosu) (用Gosu编码)
enum Status {
ACTIVE,INACTIVE,UNKNOWN;
public function doSomething(){
switch (this) {
case INACTIVE:
//do something
break;
case ACTIVE:
//do something
break;
case UNKNOWN:
//do something
break;
}
}
}
Now you have the capability to call the doSomething()
method from the enum constants
in your main code 现在,您可以从主代码中的
enum constants
调用doSomething()
方法
Example: 例:
var a=Status.ACTIVE
var b=Status.INACTIVE
var c=Status.UNKNOWN
a.doSomething()
b.doSomething()
c.doSomething()
As you can read in Gosu grammar or below function
is not allowed inside enum consts, even brackets {}
after consts are not allowed. 正如您可以在Gosu语法中阅读的那样, 枚举const内不允许使用
function
,甚至const后面的方括号{}
也不允许。
What is allowed in enum body: 枚举正文中允许的内容:
enumBody = "{" [enumConstants] classMembers "}" .
enumConstants = enumConstant {"," enumConstant} [","] [";"] .
enumConstant = {annotation} id optionalArguments .
So basically in GOSU enum contains consts and rest normally as in any other class. 因此,基本上,在GOSU中,枚举包含const并像其他任何类一样正常休息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.