简体   繁体   中英

Why can you use just the alias to declare a enum and not the .NET type?

This works perfectly..

public  enum NodeType : byte
{ Search, Analysis, Output, Input, Audio, Movement} 

This returns a compiler error...

public  enum NodeType : Byte
{ Search, Analysis, Output, Input, Audio, Movement} 

Same happen when using reflection...

So, does somebody know why the enum -base is just an integral-type?

Probably it is just a incomplete compiler implementation (while documented).

Technically, this should work too, but it doesn't.

using x = System.Byte;

public  enum NodeType : x
{ Search, Analysis, Output, Input, Audio, Movement}

So the parser part of the compiler just allows the fixed list byte, sbyte, short, ushort, int, uint, long, or ulong . There is no technical restriction I am aware of.

Because the specs say so:

enum-declaration:
attributesopt enum-modifiersopt enum identifier enum-baseopt enum-body ;opt

enum-base:
: integral-type

enum-body:
{ enum-member-declarationsopt }
{ enum-member-declarations , }

Each enum type has a corresponding integral type called the underlying type of the enum type. This underlying type must be able to represent all the enumerator values defined in the enumeration. An enum declaration may explicitly declare an underlying type of byte, sbyte, short, ushort, int, uint, long or ulong. Note that char cannot be used as an underlying type. An enum declaration that does not explicitly declare an underlying type has an underlying type of int.

...

integral-type is defined as,

integral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char

Byte, Int32 etc are objects. Since enums require integral types and these are not, you get a compiler error. C#'s enum definition is much closer to C in that respect.

This is very different from Java, where enums are a misnomer since they are really named singletons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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