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也是可以继承类的。。。。

    作者:一修先生
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    【原】iOS学习之XML与JSON两种数据结构比较和各自底层实现
    ios 10 访问设置问题
    蛇形输出
    苹果内购流程详解
    iOS多线程比较
    App iCON 尺寸
    学习网站
    c++ lesson 一(命名空间输入输出)
    iOS中WebSocket的使用
    MAC TXT文本
  • 原文地址:https://www.cnblogs.com/1971ruru/p/1715630.html
Copyright © 2011-2022 走看看