IL 代码将 Int16 加载为 Int32

本文关键字:Int32 加载 Int16 代码 IL | 更新日期: 2023-09-27 18:25:06

以下C#代码:

short first = 1;
short second = 2;
bool eq1 = (first.Equals(second));

代码转换为:

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

ldloca.s 00 - 具有索引indx的局部变量的加载地址,简称。

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

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

IL 代码将 Int16 加载为 Int32

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