简单整数枚举
我是枚举
的新手,我想创建一个枚举来将整数与更容易理解的定义进行比较。
if (getFruit() == myEnum.APPLE) {
// ...
}
而不是
if (getFruit() == 1) {
// ...
}
Where getFruit()
返回诸如1
、2
等值
I'm new with enums
and I'd like to create one to compare an integer to a more comprehensible definition.
if (getFruit() == myEnum.APPLE) {
// ...
}
instead of
if (getFruit() == 1) {
// ...
}
Where getFruit()
returns values like 1
,2
and so on
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您错过了枚举的要点...您使用它们而不是“老派”
int
常量。看看这个:
You are missing the point of enums... you use them instead of "old school"
int
constants.Have a look at this:
您可以使用 getFruit() == myEnum.APPLE.ordinal() ,其中 ordinal 是您在文件中声明枚举的顺序。
在这种情况下,APPLE 的序数是 0,ORANGE 是 1,BANANA 是 2。
或者您可以执行以下操作:
但是,我只是让
getFruit()
返回一个枚举。You can use
getFruit() == myEnum.APPLE.ordinal()
where ordinal is the order you declare the enums in your file.The ordinal for APPLE in this case is 0, ORANGE is 1, BANANA is 2.
Or you could do the following:
However, I would just make
getFruit()
return an enum.您可以创建这样的枚举
您还可以查看此 教程
You can create an enum like this
You can also check this tutorial
getFruit 必须返回 Fruit enum
现在你可以使用
如果你使用 enum,最好使用 switch-case
getFruit must return Fruit enum
Now you can use
And if you use enum, its better to use switch-case