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

    作者:一修先生
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    python学习之调试:
    python学习之调试 错误捕捉及处理
    python之面向对象
    python学习之模块:
    python学习之内部函数:
    python学习之高级特性:
    python学习之结构语句
    python学习之列表元组,字典
    getopt使用例子
    找到系统盘被打满文件
  • 原文地址:https://www.cnblogs.com/1971ruru/p/1715630.html
Copyright © 2011-2022 走看看