简体   繁体   English

Java如何打开枚举?

[英]How does Java switch on an enumeration?

I'm coming from c#, and find java's switch statement a bit confusing. 我来自c#,发现Java的switch语句有点令人困惑。

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? 您为什么要向枚举添加方法?

It sounds like the assumption behind your question is false. 听起来您的问题背后的假设是错误的。 You can switch on enum values, integer types ( char , int , byte , etc.), or String instances. 您可以打开enum值,整数类型( charintbyte等)或String实例。

Internally, all switches compile to one of two instructions, lookupswitch or tableswitch . 在内部,所有开关都编译为以下两条指令之一: lookupswitchtableswitch Both instructions require that each case be labeled with a distinct integer. 两条指令都要求每种情况都标有不同的整数。 When you use an enum value, the "ordinal" of the value is used. 使用enum值时,将使用该值的“普通”。 When using String instances, the compiler inserts additional code to map each string to a unique value. 使用String实例时,编译器将插入其他代码,以将每个字符串映射到唯一值。 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. enum上的方法与其他对象上的方法具有相同的目的。 You can use them to implement polymorphic behavior, or as simple accessors, or whatever. 您可以使用它们来实现多态行为,也可以将其用作简单的访问器,等等。

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. 在C#中,枚举是带有某些语法糖的限制整数,在Java中,枚举是实际的类。 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 而不是做

switch(planet){
   case Mars: doWhatMarsDo();break;
   case Earth: doWhatEarthDo();break;
}

you can write 你可以写

planet.doYourThing();

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. 即使使用了枚举属性和方法也能很好地实现本教程的示例 ,但也不过分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM