[英]C# BaseType of enum
I have a enum Color
, it may derive from long
or byte
or int
, and I want to know what type does it really derive from, long
or byte
or int
?我有一个enum Color
,它可能源自long
或byte
或int
,我想知道它真正源自什么类型, long
或byte
或int
? In the process, I have met 2 problems.在这个过程中,我遇到了2个问题。
First, the Color
is defined like below:首先, Color
定义如下:
enum Color : long
{
red = 1,
black = 2,
blue = 3
}
I write the code below to do such things:我写下面的代码来做这些事情:
Console.WriteLine(typeof(Color)); // ConsoleApp7.Color
Console.WriteLine(typeof(Color).BaseType); // System.Enum
At this moment, I met my first problem: it's curious that typeof(Color).BaseType
is System.Enum
, because Color
is a enum
type.这时,我遇到了我的第一个问题:奇怪的是typeof(Color).BaseType
是System.Enum
,因为Color
是一个enum
类型。
So I'm wondering that whether you defining a enum
type like enum Enum1 { ... }
, it actually means that: class Enum1 : enum { ... }
?所以我想知道你是否定义了一个像enum Enum1 { ... }
这样的enum
类型,它实际上意味着: class Enum1 : enum { ... }
?
Based on problem 1, if I want to get its real base type, I need to write:基于问题 1,如果我想得到它真正的基类型,我需要写:
Console.WriteLine(typeof(Color).BaseType.BaseType);
Its output is System.ValueType
, we know that int
, byte
and long
all are System.ValueType
, how can I get the keyword long ?它的输出是System.ValueType
,我们知道int
、 byte
和long
都是System.ValueType
,我怎么才能得到关键字long ?
Thanks.谢谢。
You want an Underlying type, not Base type:你想要一个底层类型,而不是基础类型:
var underlyingType = Enum.GetUnderlyingType(typeof(ConsoleColor))
Also note that any specific enum (like your Color
) is a value type and base type of System.Enum
is System.ValueType
(despite the fact that System.Enum
is a reference type).另请注意,任何特定的枚举(如您的Color
)都是值类型, System.Enum
基类型是System.ValueType
(尽管System.Enum
是引用类型)。 That's why your typeof(Color).BaseType.BaseType
equals System.ValueType
这就是为什么你的typeof(Color).BaseType.BaseType
等于System.ValueType
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.