简体   繁体   English

枚举的 C# BaseType

[英]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 ,它可能源自longbyteint ,我想知道它真正源自什么类型, longbyteint 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
}

Problem 1问题一

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).BaseTypeSystem.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 { ... }

Problem 2问题二

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 ,我们知道intbytelong都是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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM