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

    作者:一修先生
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Linux安装oracle 10g常见问题之——ORA-01078,LRM-00109,ORA-01102
    Linux安装oracle 10g常见问题之——OUI-25031
    C#中static静态变量的用法
    让DIV中的内容水平和垂直居中
    json对象与json字符串互换
    AJAX请求 $.post方法的使用
    .NET(c#)new关键字的三种用法
    创建数据库和表的SQL语句
    SQL、LINQ、Lambda 三种用法(转)
    AJAX中UPDATEPANEL配合TIMER控件实现局部无刷新
  • 原文地址:https://www.cnblogs.com/1971ruru/p/1715630.html
Copyright © 2020-2023  润新知