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

后端 未结 8 803
刺人心
刺人心 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:24

    Extracted from MSDN:

    The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

    So, the cast is possible, but you need to force it:

    The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is needed to convert from enum type to an integral type.

    When you box your enum into object, the animal object is derived from System.Enum (the real type is known at runtime) so it's actually an int, so the cast is valid.

    • (animal is Enum) returns true: For this reason you can unbox animal into an Enum or event into an int doing an explicit casting.
    • (animal is int) returns false: The is operator (in general type check) does not check the underlying type for Enums. Also, for this reason you need to do an explicit casting to convert Enum to int.

提交回复
热议问题