0

如何在不优化的情况下在调试模式下构建 .NET 程序集?

dotnet build --configuration Debug

我使用上述命令构建了一个简单的 .Net Core 控制台应用程序,但编译器仍然优化了我的代码,我该怎么做才能防止它呢?

这是我原来的阶乘函数:

public int Factorial(int num)
{
    int num_aux;
    if (num < 1) num_aux = 1;
    else num_aux = num * (this.Factorial(num - 1));
    return num_aux;
}

.NET Reflector 输出反编译的函数。如您所见,编译器删除了局部变量num_aux

public int Factorial(int num)
{
    if (num < 1)
    {
        return 1;
    }
    return (num * this.Factorial(num - 1));
}

输出:

.method public hidebysig instance int32 ComputeFac(int32 num) cil managed
{
    .maxstack 4
    .locals init (
        [0] int32 num2,
        [1] bool flag,
        [2] int32 num3)
    L_0000: nop 
    L_0001: ldarg.1 
    L_0002: ldc.i4.1 
    L_0003: clt 
    L_0005: stloc.1 
    L_0006: ldloc.1 
    L_0007: brfalse.s L_000d
    L_0009: ldc.i4.1 
    L_000a: stloc.0 
    L_000b: br.s L_0019
    L_000d: ldarg.1 
    L_000e: ldarg.0 
    L_000f: ldarg.1 
    L_0010: ldc.i4.1 
    L_0011: sub 
    L_0012: call instance int32 Fac::ComputeFac(int32)
    L_0017: mul 
    L_0018: stloc.0 
    L_0019: ldloc.0 
    L_001a: stloc.2 
    L_001b: br.s L_001d
    L_001d: ldloc.2 
    L_001e: ret 
}
4

0 回答 0