c# - 为什么 C# 编译器会在 IL 中发出额外的操作码?

标签 c# cil il opcode

如果我有一个方法 Multiply 定义为:

public static class Experiment
{
    public static int Multiply(int a, int b)
    {
        return a * b;
    }
}

那么为什么编译器会发出这个 IL:

.method public hidebysig static int32 Multiply(int32 a, int32 b) cil managed
{
    .maxstack 2              //why is it not 16?
    .locals init (
        [0] int32 CS$1$0000) //what is this?
    L_0000: nop              //why this?
    L_0001: ldarg.0 
    L_0002: ldarg.1 
    L_0003: mul 
    L_0004: stloc.0          //why this?
    L_0005: br.s L_0007      //why this?
    L_0007: ldloc.0          //why this?
    L_0008: ret 
}

如您所见,它还包含一些对我来说没有意义的额外 OpCodes,而实际上我期望的是以下 IL:

.method public hidebysig static int32 MyMethod(int32 a, int32 b) cil managed
{
    .maxstack 16
    L_0000: ldarg.0 
    L_0001: ldarg.1 
    L_0002: mul 
    L_0003: ret 
}

它做同样的事情。

所以问题是,为什么编译器会在 IL 中发出额外的操作码?

我正在使用 Debug模式。

最佳答案

主要用于调试和断点支持;在这里查看答案:Why are these nop instructions in my debug build?

关于c# - 为什么 C# 编译器会在 IL 中发出额外的操作码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7672624/

相关文章:

c# - DateTime 对象未从 MSIL 返回正确的值

c# - 非赋值类的调用方法

c# - 在生成的 IL 代码中,缺少一些行。 in between 行执行什么任务?

c# - 澄清 IL 生成的引用字符串的代码

c# - 如何使用 C# 开发聊天机器人

c# - 当 kind 为 Utc 时从日期时间 UTC 转换为 datetimeoffset 时出错

c# - 有没有办法查看 DynamicMethod 生成的 x86 汇编代码?

c# - 如何控制 .Net 在命名空间冲突中选择哪个程序集?

c# - Metro WinRT 应用程序中的 AesManaged 解密

具有相同方法名称的 C# 接口(interface)