Java 如何开启枚举?
我来自 c#,发现 java 的 switch 语句有点令人困惑。
您只能打开一个字符,但可以打开一个枚举。
这是因为它在内部切换该值吗?
为什么要向枚举添加方法?
I'm coming from c#, and find java's switch statement a bit confusing.
You can only switch on a character, yet you can switch on an enumeration.
Is this because it switches internally on the value?
Why would you want to add methods to an enumeration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来你的问题背后的假设是错误的。您可以打开
enum
值、整数类型(char
、int
、byte
等)或 < code>String 实例。在内部,所有开关都编译为两个指令之一:
lookupswitch
或tableswitch
。两条指令都要求每种情况都用不同的整数进行标记。当您使用enum
值时,将使用该值的“序数”。使用String
实例时,编译器会插入附加代码以将每个字符串映射到唯一值。其他类型直接使用。您可以在另一个答案中阅读有关此内容的更多信息。enum
上的方法与任何其他对象上的方法。您可以使用它们来实现多态行为,或者作为简单的访问器,或者其他什么。It sounds like the assumption behind your question is false. You can switch on
enum
values, integer types (char
,int
,byte
, etc.), orString
instances.Internally, all switches compile to one of two instructions,
lookupswitch
ortableswitch
. Both instructions require that each case be labeled with a distinct integer. When you use anenum
value, the "ordinal" of the value is used. When usingString
instances, the compiler inserts additional code to map each string to a unique value. Other types are used directly. You can read more about this in another answer.Methods on an
enum
serve the same purpose as methods on any other object. You can use them to implement polymorphic behavior, or as simple accessors, or whatever.关于“为什么要向枚举添加方法?”
在 C# 中,枚举是带有一些语法糖的受限整数,在 Java 中,枚举是实际的类。确实有不同。您可以将方法添加到枚举中,其原因与将其添加到任何其他类中的原因相同,以使其执行操作!举个例子,每次你使用 switch 烤箱和枚举时,你都可以完美地使用枚举上的方法而不是 switch,并且更加面向对象。如果您需要在多个地方切换相同的枚举,那么您可能最好使用一种方法
而不是做
你可以写
Regarding "Why would you want to add methods to an enumeration?"
In c# an enum is a restricted integer with some syntactic sugar, in java an enum is an actual class. There are really different. You can add a method to an enum for the same reason you add it to any other class, to make it do things! As an example, every time you use a switch oven an enum you could perfectly use a method on the enum instead of switch, and be more object oriented. And if you need to switch over the same enum in more than one place, you probably would be better of using a method
instead of doing
you can write
第二个问题:因为有时候枚举需要方法,比如获取属性、进行计算等。枚举方法非常方便,可以玩一些有趣的游戏。
即使教程的示例也不是过度做作,使用枚举属性和方法效果良好。
Secondary question: because sometimes enums need methods, like to get properties, do calculations, etc. Enum methods are tremendously handy and allow some interesting games to be played.
Even the tutorial's example isn't overly-contrived, using enum properties and methods to good effect.