ToString()方法为什么不涉及装箱和拆箱操作

看到这么一个算法题目:将一整型数字转换成字符串输出

于是想到Int32.ToString()。

在.NET源代码里面,最后只得到下面结果:

 

public override string ToString()
{
return Number.FormatInt32(this, null, NumberFormatInfo.CurrentInfo);
}

[MethodImpl(MethodImplOptions.InternalCall)]
public static extern string FormatInt32(int value, string format, NumberFormatInfo info);



 

 

 

FormatInt32是交由CLR底层实现了。。

今天在Google Int32.ToString()的内部实现时,没得到答案,但却发现这个问题:ToString()方法为什么不涉及装箱和拆箱操作

 

其实在CLR via C#里面已经写的很清楚了(CLR via C#3edition P139)

Calling ToString In the call to ToString, p1 doesn’t have to be boxed. At first, you’d
think that p1 would have to be boxed because ToString is a virtual method that is
inherited from the base type, System.ValueType. Normally, to call a virtual method,
the CLR needs to determine the object’s type in order to locate the type’s method
table. Since p1 is an unboxed value type, there’s no type object pointer. However, the
just-in-time (JIT) compiler sees that Point overrides the ToString method, and it emits
code that calls ToString directly (nonvirtually) without having to do any boxing. The
compiler knows that polymorphism can’t come into play here since Point is a value
type, and no type can derive from it to provide another implementation of this virtual
method. Note that if Point's ToString method internally calls base.ToString(), then
the value type instance would be boxed when calling System.ValueType's ToString
method.

虽然int32继承自System.ValueType(CLASS),但是它override了基类的ToString(),Int32是没必要装成object的。而且Int32是ValueType

通过Google让我认识到了原来struct也是可以继承类的。。。。

posted @ 2010-04-19 20:19  一修先生  阅读(1011)  评论(1编辑  收藏  举报