How to convert from System.Enum to base integer?(如何从 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)是不可能的.请注意,这也是危险的",因为枚举可以有不同的底层类型(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 ValueTypes), so the explicit cast cannot be correct within the type system
这篇关于如何从 System.Enum 转换为基本整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 System.Enum 转换为基本整数?
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
