How is it that an enum derives from System.Enum and is an integer at the same time?

后端 未结 8 814
刺人心
刺人心 2021-01-30 16:51

Edit: Comments at bottom. Also, this.


Here\'s what\'s kind of confusing me. My understanding is that if I have an enum like this...



        
8条回答
  •  攒了一身酷
    2021-01-30 17:21

    While enum types are inherited from System.Enum, any conversion between them is not direct, but a boxing/unboxing one. From C# 3.0 Specification:

    An enumeration type is a distinct type with named constants. Every enumeration type has an underlying type, which must be byte, sbyte, short, ushort, int, uint, long or ulong. The set of values of the enumeration type is the same as the set of values of the underlying type. Values of the enumeration type are not restricted to the values of the named constants. Enumeration types are defined through enumeration declarations

    So, while your Animal class is derived from System.Enum, it's actually an int. Btw, another strange thing is System.Enum is derived from System.ValueType, however it's still a reference type.

提交回复
热议问题