c# 所有类型都是从object继承,那么值类型默认也有装箱吗?

我们知道,c#所有类型都是从System.Object继承,int等值类型也逃脱不了这种命运,那难道值类型默认有装箱操作吗?答案是否,在CLR via这本书中有简短的解释说明:

1、值类型从System.ValueType派生,虽然提供了与System.Object相同的方法,但是他重写了这些方法,而且它是隐式密封的。

2、System.Object的GetType方法返回存储在制定对象的“类型对象指针”成员中的地址,这样就可以判断系统中任何对象的真实类型。而且托管堆上所有对象都有的额外成员:同步快索引和类型对象指针,所有未装箱值类型没有同步快索引和类型对象指针。

3、Even though unboxed value types don’t have a type object pointer, you can still call virtual methods (such as Equals, GetHashCode, or ToString) inherited or overridden by the type. If your value type overrides one of these virtual methods, then the CLR can invoke the method nonvirtually because value types are implicitly sealed and cannot have any types derived from them. In addition, the value type instance being used to invoke the virtual method is not boxed. However, if your override of the virtual method calls into the base type's implementation of the method, then the value type instance does get boxed when calling the base type's implementation so that a reference to a heap object gets passed to the this pointer into the base method

这段话的意思是:

即使未装箱的值类型没有类型对象指针,您仍然可以调用该类型继承或重写的虚拟方法(例如Equals、GetHashCode或ToString)。如果值类型复盖这些虚方法之一,那么CLR可以非强制调用方法,因为值类型是隐式密封的,不能从中派生任何类型。此外,用于调用虚方法的值类型实例没有装箱。但是,如果对虚拟方法的重写调用基类型的方法实现,那么在调用基类型的实现时,值类型实例就会被装箱,以便将堆对象的引用传递给这个指针到基方法。

经典案例:

var a=(System.ValueType)1;会发生装箱吗?答案是会

猜你喜欢

转载自www.cnblogs.com/wccfsdn/p/11945596.html