如何将枚举值转换为int? [英] How to convert enum value to int?

查看:1790
本文介绍了如何将枚举值转换为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; //这个值会不同

public int getTaxValue()
{
//这里做什么?
// return(int)var;
}


解决方案

枚举公开,例如

  public enum Tax {
NONE(0),SALES(10),IMPORT(5);

private final int value;
私人税(int value){
this.value = value;
}

public int getValue(){
返回值;
}
}

...

public int getTaxValue(){
Tax tax = Tax.NONE; // or whatever
return tax.getValue();
}

(我已将名称更改为传统和可读性, btw。)



这是假设你想要在构造函数中分配的值。如果这不是你想要的,你需要给我们更多的信息。


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;
}

解决方案

You'd need to make the enum expose value somehow, e.g.

public enum Tax {
    NONE(0), SALES(10), IMPORT(5);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

...

public int getTaxValue() {
    Tax tax = Tax.NONE; // Or whatever
    return tax.getValue();
}

(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.

这篇关于如何将枚举值转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆