如何从 System.Enum 转换为基本整数?

How to convert from System.Enum to base integer?(如何从 System.Enum 转换为基本整数?)
本文介绍了如何从 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 没有直接的继承关系(尽管两者都是 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 转换为基本整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)