ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 为什么Int32.ToString()发出调用指令而不是callvirt?

2019-05-27 20:51:46  阅读:341  来源: 互联网

标签:c net clr cil boxing


对于以下代码段:

struct Test
{
    public override string ToString()
    {
        return "";
    }
}

public class Program
{
    public static void Main()
    {
        Test a = new Test();
        a.ToString();
        Int32 b = 5;
        b.ToString();
    }
}

编译器发出以下IL:

  .locals init ([0] valuetype ConsoleApplication2.Test a,
           [1] int32 b)
  IL_0000:  nop
  IL_0001:  ldloca.s   a
  IL_0003:  initobj    ConsoleApplication2.Test
  IL_0009:  ldloca.s   a
  IL_000b:  constrained. ConsoleApplication2.Test
  IL_0011:  callvirt   instance string [mscorlib]System.Object::ToString()
  IL_0016:  pop
  IL_0017:  ldc.i4.5
  IL_0018:  stloc.1
  IL_0019:  ldloca.s   b
  IL_001b:  call       instance string [mscorlib]System.Int32::ToString()
  IL_0020:  pop
  IL_0021:  ret

由于值类型Test和Int32都覆盖了ToString()方法,我认为a.ToString()和b.ToString()都不会发生装箱.因此我想知道为什么编译器为Test发出约束的callvirt,并调用Int32?

解决方法:

这是编译器对原始类型进行的优化.

但即使对于自定义结构,由于受约束,callvirt实际上也会在运行时作为调用执行.操作码 – 在方法被覆盖的情况下.它允许编译器在任何一种情况下发出相同的指令,并让运行时处理它.

MSDN开始:

If thisType is a value type and thisType implements method then ptr is passed unmodified as the this pointer to a call method instruction, for the implementation of method by thisType.

和:

The constrained opcode allows IL compilers to make a call to a virtual function in a uniform way independent of whether ptr is a value type or a reference type. Although it is intended for the case where thisType is a generic type variable, the constrained prefix also works for nongeneric types and can reduce the complexity of generating virtual calls in languages that hide the distinction between value types and reference types.

我不知道有关优化的任何官方文档,但您可以在Ros001 repo中看到MayUseCallForStructMethod method的评论.

至于为什么这种优化被推迟到非原始类型的运行时,我相信这是因为实现可以改变.想象一下,引用一个最初具有ToString覆盖的库,然后将DLL(不重新编译!)更改为删除覆盖的那个.这会导致运行时异常.对于原语,他们可以肯定它不会发生.

标签:c,net,clr,cil,boxing
来源: https://codeday.me/bug/20190527/1166140.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有