C# 的 Java 等价物是什么:
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
,但这不是他们所做的在 example on the Sun website .
关于c# - Java中具有int值的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1681976/