如何转换System.Enum基地整数? [英] How to convert from System.Enum to base integer?

查看:137
本文介绍了如何转换System.Enum基地整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个通用的方法,任何System.Enum派生类型转换成其对应的整数值,无铸造和preferably没有解析字符串。

I'd like to create a generic method for converting any System.Enum derived type to its corresponding integer value, without casting and preferably without parsing a string.

比如说,我想是这样的:

Eg, what I want is something like this:

// Trivial example, not actually what I'm doing.
class Converter
{
    int ToInteger(System.Enum anEnum)
    {
        (int)anEnum;
    }
}

但是,这并不出现工作。 ReSharper的报告,你不能投类型'System.Enum'的前pression键入'诠释'。

But this doesn't appear to work. Resharper reports that you can not cast expression of type 'System.Enum' to type 'int'.

现在,我想出了这个解决方案,但我宁愿有一些更有效。

Now I've come up with this solution but I'd rather have something more efficient.

class Converter
{
    int ToInteger(System.Enum anEnum)
    {
        return int.Parse(anEnum.ToString("d"));
    }
}

有什么建议?

推荐答案

如果你不想投,

Convert.ToInt32()

可以做的伎俩。

could do the trick.

直接投(通过(INT)enumValue )是不可能的。请注意,这也将是危险的,因为一个枚举可以有不同的基础类型( INT 字节 ...)。

The direct cast (via (int)enumValue) is not possible. Note that this would also be "dangerous" since an enum can have different underlying types (int, long, byte...).

更正式的: System.Enum 的Int32 没有直接的继承关系(虽然两者都是值类型 S),所以显式转换不能在类型系统内是正确的。

More formally: System.Enum has no direct inheritance relationship with Int32 (though both are ValueTypes), so the explicit cast cannot be correct within the type system

这篇关于如何转换System.Enum基地整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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