问题描述
我想创建一个通用方法,用于将任何 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
)是不可能的.请注意,这也是危险的",因为枚举可以有不同的底层类型(int
、long
、byte
...).
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
没有直接的继承关系(尽管两者都是 ValueType
),所以显式转换不能在类型系统中是正确的
More formally: System.Enum
has no direct inheritance relationship with Int32
(though both are ValueType
s), so the explicit cast cannot be correct within the type system
这篇关于如何从 System.Enum 转换为基本整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!