如何将枚举值转换为int?
我有一个返回 int 类型的函数。但是,我只有 TAX 枚举的值。
如何将 TAX 枚举值转换为 int?
public enum TAX {
NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);
private int value;
private TAX(int value){
this.value = value;
}
}
TAX var = TAX.NOTAX; // This value will differ
public int getTaxValue()
{
// what do do here?
// return (int)var;
}
I have a function which return a type int. However, I only have a value of the TAX enumeration.
How can I cast the TAX enumeration value to an int?
public enum TAX {
NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);
private int value;
private TAX(int value){
this.value = value;
}
}
TAX var = TAX.NOTAX; // This value will differ
public int getTaxValue()
{
// what do do here?
// return (int)var;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您需要以某种方式使枚举公开
value
,例如(顺便说一句,我已将名称更改为更加传统和可读。)
这是假设您想要在构造函数中分配的值。如果这不是您想要的,您需要向我们提供更多信息。
You'd need to make the enum expose
value
somehow, e.g.(I've changed the names to be a bit more conventional and readable, btw.)
This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.
我更喜欢这个:
那么:
I prefer this:
then:
有时,一些 C# 方法会让 Java 世界的生活变得更轻松……:
Sometime some C# approach makes the life easier in Java world..:
如果您想要在构造函数中分配的值,则需要在枚举定义中添加一个方法来返回该值。
如果您想要一个代表枚举值的唯一数字,可以使用
ordinal()
。If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.
If you want a unique number that represent the enum value, you can use
ordinal()
.也许使用字符串表示比使用整数更好,因为如果将值添加到枚举中,字符串仍然有效。您可以使用枚举的 name() 方法将枚举值转换为字符串,并使用枚举的 valueOf() 方法再次从字符串创建枚举表示形式。以下示例演示如何将枚举值转换为字符串并返回(ValueType 是一个枚举):
Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):
如果您想从 profileType 获取 int,您可以简单地执行以下操作:
int profileTypeInt = profileType.ordinal();
If you want to get int from profileType you can simply do:
int profileTypeInt = profileType.ordinal();
一种稍微不同的方法(至少在 Android 上)是使用 IntDef 注释来组合一组 int 常量
用作函数参数:
或在变量声明中:
A somewhat different approach (at least on Android) is to use the IntDef annotation to combine a set of int constants
Use as function parameter:
or in a variable declaration: