gpt4 book ai didi

c# - Java中具有int值的枚举

转载 作者:IT老高 更新时间:2023-10-28 20:29:56 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com