Java 中具有 int 值的枚举
Java 中 C# 的等价物是什么:
enum Foo
{
Bar = 0,
Baz = 1,
Fii = 10,
}
What's the Java equivalent of C#'s:
enum Foo
{
Bar = 0,
Baz = 1,
Fii = 10,
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想要
enum
的属性,您需要像这样定义它:您可以像这样使用它:
要意识到
enum
只是创建的快捷方式一个类,因此您可以向该类添加所需的任何属性和方法。如果您不想在
enum
上定义任何方法,您可以更改成员变量的范围并使它们public
,但这不是它们在中所做的事情。 href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" rel="noreferrer">Sun 网站上的示例。
If you want attributes for your
enum
you need to define it like this:You'd use it like this:
The thing to realise is that
enum
is just a shortcut for creating a class, so you can add whatever attributes and methods you want to the class.If you don't want to define any methods on your
enum
you could change the scope of the member variables and make thempublic
, but that's not what they do in the example on the Sun website.如果您有一个连续的值范围,并且您需要的只是整数值,您可以最少地声明枚举:
然后按如下方式获取 int 值:
但是,如果您需要一个不连续的范围(如您的示例中所示,其中你从 1 跳到 10)然后你需要编写自己的枚举构造函数来设置你自己的成员变量,并为该变量提供一个 get 方法,如其他答案中所述。
If you have a contiguous range of values, and all you need is the integer value, you can just declare the enum minimally:
and then obtain the int value as follows:
However, if you need a discontiguous range (as in your example, where you jump from 1 to 10) then you will need to write your own enum constructor which sets your own member variable, and provide a get method for that variable, as described in the other answers here.
它是:
请注意,要从索引获取枚举的值,
Foo.valueOf(1)
(*) 是行不通的。您需要自己编写代码:(*):Enum.valueOf() 从字符串返回枚举。因此,您可以使用
Foo.valueOf('Bar')
获取 Bar 值It is:
Note that to get the value of the enum from the index,
Foo.valueOf(1)
(*), would not work. You need do code it yourself:(*): Enum.valueOf() return the enum from a String. As such, you can get the value Bar with
Foo.valueOf('Bar')
听起来你想要这样的东西:
对于初学者来说,Sun 的 Java Enum教程将是了解更多信息的好地方。
Sounds like you want something like this:
For starters, Sun's Java Enum Tutorial would be a great place to learn more.
在 Java 中,枚举与其他类非常相似,但 Java 编译器知道在各种情况下处理方式略有不同。因此,如果您想要其中的数据,就像您似乎需要有一个数据实例变量和一个适当的构造函数。
In Java enums are very similar to other classes but the the Java compiler knows to treat a little differently in various situations. So if you want data in them like you seem to you need to have an instance variable for the data and an appropriate constructor.