IL代码将Int16加载为Int32

Ofi*_*ris 3 c# il

以下C#代码:

short first = 1;
short second = 2;
bool eq1 = (first.Equals(second));
Run Code Online (Sandbox Code Playgroud)

该代码转换为:

IL_0001:  ldc.i4.1    
IL_0002:  stloc.0     // first
IL_0003:  ldc.i4.2    
IL_0004:  stloc.1     // second
IL_0005:  ldloca.s    00 // first
IL_0007:  ldloc.1     // second
IL_0008:  call        System.Int16.Equals
IL_000D:  stloc.2     // eq1
Run Code Online (Sandbox Code Playgroud)

ldloca.s 00 - 使用索引indx,short form加载局部变量的地址.

ldloc.1 - 将局部变量1加载到堆栈上.

为什么两个命令都不是ldloca.s(两个变量都是short类型)?

小智 8

值类型的所有实例方法都有一个类型的隐式this参数ref T,而不是类型T,这就是first变量需要的原因ldloca.但是System.Int16.Equals参数是类型的System.Int16,没有任何参数ref,所以你的second变量不需要(并且不能传递)ldloca.