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

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

问题描述

我想创建一个通用方法,用于将任何 System.Enum 派生类型转换为其相应的整数值,无需强制转换,最好无需解析字符串.

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"类型的表达式转换为int"类型.

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()

可以做到这一点.

直接转换(通过 (int)enumValue)是不可能的.请注意,这也是危险的",因为枚举可以具有不同的底层类型(intlongbyte...).

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.EnumInt32 没有直接的继承关系(虽然都是 ValueTypes),所以显式转换不能在类型系统中是正确的

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天全站免登陆