c# – 为什么Int32.ToString()发出调用指令而不是callvirt?
作者:互联网
对于以下代码段:
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 andthisType
implementsmethod
thenptr
is passed unmodified as thethis
pointer to acall
method instruction, for the implementation of method bythisType
.
和:
The
constrained
opcode allows IL compilers to make a call to a virtual function in a uniform way independent of whetherptr
is a value type or a reference type. Although it is intended for the case wherethisType
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