简体   繁体   中英

How to set data type of enum class?

I am creating an enum class in java, which is already created in .NET.

This is .NET code.

public enum Bezel : byte
        {
            Flashing,
            SolidOn,
            None = 254
        }

And this is Java code i am trying.

public enum Bezel {

        Flashing,
        SolidOn,
        None = 254
    }

In the .NET code, they are extending "byte". So, how can we do the same in Java?

Enums in java are sets of objects, not sets of constants as they are in C#. So, you need to write your enum in java like this:

public enum Bezel 
(
    Flashing(0),
    SolidOn(1),
    None(254);

    public final int value;
    public Bezel( int value )
    {
        this.value = value;
    }
)

Then, when you need the actual value, do this:

Bezel b = ...;
int value = b.value;

Enums in Java and .NET are very different. In .NET, they're just named numbers, basically. In Java they're a fixed set of objects - which you can give extra behaviour etc.

Also, the C# code isn't "extending" byte - it's just using byte as the underlying type. The nearest equivalent Java code would be something like:

public enum Bezel {
    // Note different naming convention in Java
    FLASHING((byte) 0),
    SOLID_ON((byte) 1),
    NONE((byte) 254);

    private final byte value;

    private Bezel(byte value) {
        this.value = value;
    }

    public byte getValue() {
        return value;
    }
}

Note that if you print out Bezel.NONE.getValue() , it will print -2, because Java's byte type is signed whereas it's unsigned in C#. There's no unsigned byte type in Java - but you could always use short or int instead, to cover the 0-255 range (and more, of course).

You may also want a method to retrieve a Bezel given its value - something you could do in C# just by casting. We don't know how you're going to use the enum though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM