枚举的表示
枚举在编程语言中如何“在幕后”工作?我猜测每种语言都有不同的方式来表示这些数据类型。
在java中,您可以使用==运算符,例如:
public class TestEnum {
private enum Test {
foo, bar
}
public static void main(String[] args) {
System.out.println(Test.foo == Test.foo); // returns true
}
}
在==期间,枚举类型是否转换为原始类型?或者枚举值是单例吗? C# 是否以与 Java 相同的方式利用枚举?与编程语言相比,数据库枚举类型的处理方式是否有所不同?
How do enums work 'behind the scenes' in programming languages? I am guessing that each language has a different way of representing these datatypes.
In java you can use the == operator, for example:
public class TestEnum {
private enum Test {
foo, bar
}
public static void main(String[] args) {
System.out.println(Test.foo == Test.foo); // returns true
}
}
Is an enum type converted to a primitive during the ==? Or is the enum value a Singleton? Does C# leverage enums in the same manner as java? Are database enum types treated differently compared to programming languages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Java
enum
使用了很多的技巧,使其仍然是对象,但可以与==
一起使用。原始的类型安全枚举模式(另请参阅有效Java)可以提供一些见解,但是Enum.java source 将向您展示他们现在是如何做到的。Java
enum
s make use of a lot of tricks to still be objects but work with==
. The original typesafe enum pattern (see also Effective Java) can provide some insight, but the Enum.java source will show you exactly how they do it now.Java 中的枚举类型实际上是一个特殊的编译器生成的类,而不是算术类型:枚举值表现为全局预生成实例,以便比较引用来代替 equals。
您可以反汇编 .class 文件来验证它:
它应该大致相当于以下 Java 代码:
为了简单起见,您可以将其视为字符串驻留的特殊情况。
An enum type in Java is actually a special compiler-generated class rather than an arithmetic type: enum values behave as global pre-generated instances in order to compare references in place of
equals
.You can verify it disassembling a .class file:
it should roughly equivalent to the following Java code:
For the sake of simplicity you can think it as a special case of string interning.
我认为大多数语言都会在幕后将枚举转换为
int
- 尽管这当然不是必需的。例如 - 在上面的示例中,编译器当然有可能意识到这两个值相等,而无需将它们转换为某种中间表示形式,而只是发出一个
true
值。I think that most languages convert enums into
int
behind the scenes - although that certainly isn't requirement.For example - in your example above it is certainly possible that the compiler realizes that the two values are equal without ever converting them to some intermediate representation and just emits a
true
value.我认为枚举只是常量整数。
所以你可以
等编译器向它们添加命名空间“Test”
I would think enums are simply const integers.
so you have
and so on with the compiler adding the namespace 'Test' to them
.Net语言以整数的形式表示它们。
如果你这样做
If 1 == foo ,这应该返回 true
我通常更容易理解的是:
尝试一下,用字符串更改 1 和 2 。这应该会引发编译器错误。
.Net language represent them in form of integers.
If you do
If 1 == foo , this should return true
What I would usually to be easier to understand is this :
Give it a try, change the 1 and 2 with strings. This should throw you a compiler error.