zoukankan      html  css  js  c++  java
  • 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也是可以继承类的。。。。

    作者:一修先生
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    关于wepy小程序图片显示问题
    输入地址到页面显示发生了写什么?
    一次Debug过程的思考
    一次冗长繁琐的排错经历
    PHP内核探索之变量(7)- 不平凡的字符串
    PHP内核探索之变量(6)- 后续内核探索系列大纲备忘
    PHP内核探索之变量(5)- session的基本原理
    PHP内核探索之变量(4)- 数组操作
    PHP内核探索之变量(3)- hash table
    PHP内核探索之变量(2)-理解引用
  • 原文地址:https://www.cnblogs.com/1971ruru/p/1715630.html
Copyright © 2011-2022 走看看