Java中相当于C#的是什么:
enum Foo
{
Bar = 0,
Baz = 1,
Fii = 10,
}
enum
定义属性,需要按照以下方式进行定义:public enum Foo {
BAR (0),
BAZ (1),
FII (10);
private final int index;
Foo(int index) {
this.index = index;
}
public int index() {
return index;
}
}
你会像这样使用它:
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.printf("%s has index %d%n", f, f.index());
}
}
需要认识到的是,enum
只是创建类的一种快捷方式,因此您可以向该类添加任何属性和方法。
如果您不想在 enum
上定义任何方法,则可以更改成员变量的作用域并将其设为 public
,但这不是 Sun 网站上的 example on the Sun website 中的做法。
如果您有一系列连续的值,而且您只需要整数值,则可以最小化声明枚举:
public enum NUMBERZ {
ZERO, ONE, TWO
}
然后按以下方式获取int值:
int numberOne = NUMBERZ.ONE.ordinal();
然而,如果你需要一个不连续的范围(就像你的例子中,从1跳到10),那么你需要编写自己的枚举构造函数来设置自己的成员变量,并提供一个获取该变量的方法,如其他答案所述。
这是:
enum Foo
{
Bar(0),
Baz(1),
Fii(10);
private int index;
private Foo(int index) {
this.index = index;
}
}
Foo.valueOf(1)
(*)是无法正常工作的。您需要自己编写代码实现此功能:public Foo getFooFromIndex(int index) {
switch (index) {
case 0:
return Foo.Bar;
case 1:
return Foo.Baz;
case 10:
return Foo.Fii;
default:
throw new RuntimeException("Unknown index:" + index);
}
}
(*): Enum.valueOf() 方法可以通过字符串返回枚举值。因此,你可以使用 Foo.valueOf('Bar')
获取 Bar 这个枚举值。
public enum Foo {
Bar(0),
Baz(1),
Fii(10);
private int number;
public Foo(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
首先,Sun的Java枚举教程将是一个学习更多的好地方。
public enum Foo {
Bar(0),
Baz(1),
Fii(10);
private final int someint;
Foo(int someint) {
this.someint = someint;
}
}