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

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

    A Enum's underlying type is the type used to store the value of the constants. In your example, even though you haven't explicitly defined the values, C# does this:

    enum Animal : int
    {
        Dog = 0,
        Cat = 1
    }
    

    Internally, Animal is made up of two constants with the integer values 0 and 1. That's why you can explicitly cast an integer to an Animal and an Animal to an integer. If you pass Animal.Dog to a parameter that accepts an Animal, what you are really doing is passing the 32bit integer value of Animal.Dog (in this case, 0). If you give Animal a new underlying type, then the values are stored as that type.

提交回复
热议问题