如何确定代表类型枚举值吗? [英] How to determine the represented type of enum value?

查看:148
本文介绍了如何确定代表类型枚举值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下两个实例:

enum MyEnum1 {
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

enum MyEnum2 {
     Value1 = 'a',
     Value2 = 'b',
     Value3 = 'c'
}

我可以检索这些枚举值通过代表的物理值显式类型转换,((int)的MyEnum1.Value2)== 2 ((char)的MyEnum2.Value2)=='b',但如果我想要得到的字符表示或整型表示不知道第一次投的类型是什么?

I can retrieve the physical value represented by these enum values through explicit casting, ((int)MyEnum1.Value2) == 2 or ((char)MyEnum2.Value2) == 'b', but what if I want to get the char representation or the int representation without first knowing the type to cast to?

是否有可能得到一个枚举的潜在价值没有投或者是至少编程可以确定正确类型的潜在价值?

Is it possible to get the underlying value of an enum without a cast or is it at least programatically possible to determine the correct type of the underlying value?

推荐答案

这两个枚举的基础值为 INT 。你仅仅使用一个事实,即有一个从字符 INT 在第二种情况下的隐式转换。

The underlying value of both of those enums is int. You're just using the fact that there's an implicit conversion from char to int in the second case.

例如,如果你看一下在反射器的第二枚举,你会看到这样的事情:

For example, if you look at the second enum in Reflector, you'll see something like this:

internal enum MyEnum2
{
    Value1 = 0x61,
    Value2 = 0x62,
    Value3 = 0x63
}

编辑:如果你想有一个不同的基本类型,你必须指定它,如:

If you want a different underlying type, you've got to specify it, e.g.

public enum Foo : long
{
}

然而,只有字节为sbyte USHORT INT UINT ULONG 是有效的基本枚举类型。

However, only byte, sbyte, short, ushort, int, uint, long, and ulong are valid underlying enum types.

这篇关于如何确定代表类型枚举值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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