2014-11-11 7 views
5

To działa doskonale ..Dlaczego można użyć tylko aliasu do deklarowania wyliczenia, a nie typu .NET?

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

ta zwraca błąd kompilatora ...

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

samo zdarzyć, gdy przy użyciu odbicia ...

tak, to czy ktoś wie dlaczego baza enum jest tylko typem integralnym?

+0

możliwy duplikat [Różnica między bajtem a bajtem typów danych w C#] (http://stackoverflow.com/questions/2415742/difference-between-byte-vs-byte-data-types-in-c-sharp) – Paparazzi

+0

Zobacz duplikat, który opublikowałem. W niektórych przypadkach wymagane jest użycie słowa kluczowego. – Paparazzi

Odpowiedz

6

Prawdopodobnie jest to tylko niepełna implementacja kompilatora (chociaż dokumentowana).

Pod względem technicznym powinno to również działać, ale nie działa.

using x = System.Byte; 

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

Tak więc parser, część kompilatora, pozwala tylko na ustaloną listę byte, sbyte, short, ushort, int, uint, long, or ulong. Nie znam ograniczeń technicznych.

5

Ponieważ the specs powiedzieć:

 

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.

...

integralną typu jest zdefiniowany jak

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

0

Bajt Int32 itd są obiektami. Ponieważ wyliczenia wymagają typów integralnych, a te nie są, pojawia się błąd kompilatora. Definicja wyliczeniowa C# jest znacznie bliższa C w tym zakresie.

To bardzo różni się od Javy, gdzie wyliczenia są mylące, ponieważ są tak naprawdę nazywane singletonami.

Powiązane problemy