Why Enum's HasFlag method need boxing?

前端 未结 6 808
时光取名叫无心
时光取名叫无心 2020-12-10 03:45

I am reading \"C# via CLR\" and on page 380, there\'s a note saying the following:

Note The Enum class defines a HasFlag method defined as follows

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 04:26

    Enum inherits from ValueType which is... a class! Hence the boxing.

    Note that the Enum class can represents any enumeration, whatever its underlying type is, as a boxed value. Whereas a value such as FileAttributes.Hidden will be represented as real value type, int.

    Edit: let's differentiate the type and the representation here. An int is represented in memory as 32 bits. Its type derives from ValueType. As soon as you assign an int to an object or derived class (ValueType class, Enum class), you're boxing it, effectively changing its representation to a class now containing that 32 bits, plus additional class information.

提交回复
热议问题