是 enum to int 拆箱吗?
Is enum to int unboxing?
enum Season { spring, summer, fall, winter }
int a = (int)Season.spring;
这是开箱还是普通铸造?
如果这是拆箱,你能解释一下为什么吗?
我认为这只是一个普通的转换,因为 'enum' 和 'int' 都是值类型数据。
如 ECMA-334 11.3.3 中所述,C# 定义了 enum
类型及其基础类型之间的转换:
但是,这里并没有说明是不是拆箱转换。不过,这可以从枚举和整数都是值类型的事实中推断出来,因此不涉及拆箱。
ECMA-335,它定义了 CLR,更清楚地表明 enum
不仅可以转换为整数,它实际上 是 整数,根本没有完成转换:
14.3 Enums
For binding purposes (e.g., for locating a method definition from the method reference used to call it) enums shall be distinct from their underlying type. For all other purposes, including verification and execution of code, an unboxed enum freely interconverts with its underlying type. Enums can be boxed (§13) to a corresponding boxed instance type, but this type is not the same as the boxed type of the underlying type, so
boxing does not lose the original type of the enum.
enum Season { spring, summer, fall, winter }
int a = (int)Season.spring;
这是开箱还是普通铸造? 如果这是拆箱,你能解释一下为什么吗? 我认为这只是一个普通的转换,因为 'enum' 和 'int' 都是值类型数据。
如 ECMA-334 11.3.3 中所述,C# 定义了 enum
类型及其基础类型之间的转换:
但是,这里并没有说明是不是拆箱转换。不过,这可以从枚举和整数都是值类型的事实中推断出来,因此不涉及拆箱。
ECMA-335,它定义了 CLR,更清楚地表明 enum
不仅可以转换为整数,它实际上 是 整数,根本没有完成转换:
14.3 Enums
For binding purposes (e.g., for locating a method definition from the method reference used to call it) enums shall be distinct from their underlying type. For all other purposes, including verification and execution of code, an unboxed enum freely interconverts with its underlying type. Enums can be boxed (§13) to a corresponding boxed instance type, but this type is not the same as the boxed type of the underlying type, so boxing does not lose the original type of the enum.