如何比较 enum 和 int 值? [英] How to compare enum and int values?

查看:72
本文介绍了如何比较 enum 和 int 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在每个提到的情况下,我们都将 enum 转换为 int 或将 int 转换为 enum.

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?

谢谢.

附言在当前示例中,我将其与幻数"进行比较,但在实际应用中,我从 DB 的整数字段获取数据.

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

推荐答案

不管你使用哪个,它们的表现都是一样的.如果没有整数值的枚举,.net 在运行时创建一个.没有例外.

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?

这篇关于如何比较 enum 和 int 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆