如何比较枚举和int值?int

2023-09-03 05:48:19 作者:山溪水梦

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

在每一个提到的情况下,我们有枚举的皈依为int或int枚举。

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?

感谢。

P.S。在当前的例子中,我比较'神奇的数字,但在实际应用中我得到的整数字段数据从数据库。

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

推荐答案

没关系,您使用,他们将执行相同。如果没有枚举为一个整数值,达网络创建一个在运行时。不能有任何例外。

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?