How to compare enum and int values?

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

enum MyEnum {     Invalid=0,     Value1=1,     Value1=2, }  void main () {     MyEnum e1 = MyEnum.Value1;     int i1 = 2;      // Is there any difference how to compare enumEration values with integers?     if ( e1==(MyEnum)i1 )... // 1st      if ( (int)e1==i1 )... // 2nd

In each of mentioned cases we have convertion of enum to int or int to enum.

Is there any difference in these conversions (performance, any other)? Or they are exactly the same?

Thanks.

P.S. In current example I compare to 'magic number' but in real application I am getting data from integer field from DB.

回答1:

It doesn't matter which you use, they will perform identically. If there is no enum for an integer value, .net creates one at runtime. There can be no exceptions.

However, Xichen Li is correct - why would you want to compare an enum against an integer value?



回答2:

I would recommend casting the int to the representative enum value when you read it from the database. This will greatly improve the readability of your code.

enum MyEnum {     Invalid=0,     Value1=1,     Value1=2, }  MyEnum dbValue = ReadEnumFromDB(); if(dbValue == MyEnum.Invalid) {    ... }


回答3:

I would go with the 2nd method. To me, it makes more logical sense. It would eliminate runtime exceptions if i2 is out of range.



回答4:

They are exactly the same. Displaying the generated IL using the Debug, Windows, Disassembly (Ctrl-Alt-D) gives you:

MyEnum e1 = MyEnum.Value1; 00260834  mov         dword ptr [ebp-3Ch],1   int i1 = 2; 0026083B  mov         dword ptr [ebp-40h],2    // Is there any difference how to compare enumEration values with integers? if (e1 == (MyEnum) i1)  00260842  mov         eax,dword ptr [ebp-3Ch]   00260845  cmp         eax,dword ptr [ebp-40h]   00260848  sete        al   0026084B  movzx       eax,al   0026084E  mov         dword ptr [ebp-44h],eax   00260851  cmp         dword ptr [ebp-44h],0   00260855  je          00260858   ; // 1st 00260857  nop    if ((int)e1 == i1) 00260858  mov         eax,dword ptr [ebp-3Ch]   0026085B  cmp         eax,dword ptr [ebp-40h]   0026085E  sete        al   00260861  movzx       eax,al   00260864  mov         dword ptr [ebp-48h],eax   00260867  cmp         dword ptr [ebp-48h],0   0026086B  je          0026086E   ; // 2nd 0026086D  nop  


回答5:

Enumerations in .Net are really just pretty meta-structures over the base integral type. (By default that type is int.) If you look at the Generated IL for an enumeration you will find it is really a standard type with several static fields for each of the particular enumeration elements. As such the enum can be cast between integral types transparently.

Related answer



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!