c# - 为什么反编译代码包含 foreach 循环?

标签 c# decompiling

我已经实现了一个 foreach 循环和一个 while 循环,它们应该创建几乎相同的 IL 代码。

IL 代码(使用编译器版本 12.0.40629 为 C#5 生成)确实几乎相同(除了一些数字等自然异常(exception)),但反编译器能够重现初始代码。

允许反编译器判断前一个代码块是 foreach 循环而后一个代码块代表 while 循环的关键区别是什么?

我在下面提供的反编译代码是使用最新版本(截至今天)的 ILSpy (2.3.1.1855) 生成的,但我也使用了 JustDecompile、.NET Reflector 和 dotPeek — 没有区别。我没有配置任何东西,我只是安装了工具。

原代码:

using System;
using System.Collections.Generic;

namespace ForeachVersusWhile
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var x = new List<int> {1, 2};
            foreach (var item in x)
            {
                Console.WriteLine(item);
            }

            using (var enumerator = x.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    Console.WriteLine(enumerator.Current);
                }
            }
        }
    }
}

反编译代码:

List<int> x = new List<int>
{
    1,
    2
};
foreach (int item in x)
{
    Console.WriteLine(item);
}
using (List<int>.Enumerator enumerator = x.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

IL 代码(仅限循环):

[...]
IL_0016: ldloc.0
IL_0017: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<int32>::GetEnumerator()
IL_001c: stloc.s CS$5$0000
.try
{
    IL_001e: br.s IL_002e
    // loop start (head: IL_002e)
        IL_0020: ldloca.s CS$5$0000
        IL_0022: call instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::get_Current()
        IL_0027: stloc.1
        IL_0028: ldloc.1
        IL_0029: call void [mscorlib]System.Console::WriteLine(int32)

        IL_002e: ldloca.s CS$5$0000
        IL_0030: call instance bool valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::MoveNext()
        IL_0035: brtrue.s IL_0020
    // end loop

    IL_0037: leave.s IL_0047
} // end .try
finally
{
    IL_0039: ldloca.s CS$5$0000
    IL_003b: constrained. valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>
    IL_0041: callvirt instance void [mscorlib]System.IDisposable::Dispose()
    IL_0046: endfinally
} // end handler

IL_0047: ldloc.0
IL_0048: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<int32>::GetEnumerator()
IL_004d: stloc.2
.try
{
    IL_004e: br.s IL_005c
    // loop start (head: IL_005c)
        IL_0050: ldloca.s enumerator
        IL_0052: call instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::get_Current()
        IL_0057: call void [mscorlib]System.Console::WriteLine(int32)

        IL_005c: ldloca.s enumerator
        IL_005e: call instance bool valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>::MoveNext()
        IL_0063: brtrue.s IL_0050
    // end loop

    IL_0065: leave.s IL_0075
} // end .try
finally
{
    IL_0067: ldloca.s enumerator
    IL_0069: constrained. valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32>
    IL_006f: callvirt instance void [mscorlib]System.IDisposable::Dispose()
    IL_0074: endfinally
} // end handler

问题背景:

我读过一篇文章,其中介绍了 C# 代码编译后的结果。在第一步中,他们查看了一个简单示例:foreach 循环。

MSDN 支持,foreach 循环应该“隐藏枚举器的复杂性”。 IL 代码对 foreach 循环一无所知。因此,我的理解是,在幕后,foreach 循环的 IL 代码等于使用 IEnumerator.MoveNext 的 while 循环。

因为 IL 代码不代表 foreach 循环,反编译器很难判断是否使用了 foreach 循环。这引发了几个问题,人们想知道为什么他们在反编译自己的代码时会看到一个 while 循环。这是一个example .

我想亲自看看,并编写了一个带有 foreach 循环的小程序并编译了它。然后我使用反编译器查看代码的样子。我没想到会有 foreach 循环,但当我真的得到一个时感到很惊讶。

纯 IL 代码自然包含对 IEnumerator.MoveNext 等的调用。

我想我做错了什么,因此使工具能够访问更多信息,从而正确地告诉我我正在使用 foreach 循环。那么,为什么我看到的是 foreach 循环而不是使用 IEnumerator.MoveNext 的 while 循环?

最佳答案

这是我编译的代码,这使得查看差异稍微容易一些:

using System;
using System.Collections.Generic;

class Test
{
    static void Main() {} // Just to make it simpler to compile

    public static void ForEach(List<int> x)
    {        
        foreach (var item in x)
        {
            Console.WriteLine(item);
        }
    }

    public static void While(List<int> x)
    {
        using (var enumerator = x.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                Console.WriteLine(enumerator.Current);
            }
        }
    }
}

我正在使用 Roslyn,通过 VS2015 更新 1 - 版本 1.1.0.51109。

用csc/o-/debug- Test.cs编译

在这种情况下,Reflector 9.0.1.318 可以区分...我也可以。foreach 循环的局部变量是:

.locals init (valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32> V_0,
       int32 V_1)

但是 while 循环的局部变量是:

.locals init (valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32> V_0,
       bool V_1)

while 循环中,有一个 STLoc.1/ldloc.1 对与 MoveNext(),但 不是 Current 的结果......而在 foreach 中,情况正好相反。

用csc/o+/debug- Test.cs编译

在这种情况下,Reflector 在这两种情况下都显示了一个 while 循环,并且 IL 确实相同。两个循环中都没有 STLoc.1/ldloc.1 对。

您的 IL

查看 您的 编译产生的 IL - 同样,STLoc.1/ldloc.1 对用于foreach 循环中的 Current 属性。

手工制作的 IL

我从“无法区分版本”中获取 IL,只是更改了 .locals 部分并添加了 STLoc.1/ldloc.1 进入混合,宾果游戏 - Reflector 再次认为这是一个 foreach 循环。

所以基本上,虽然我不知道其他反编译器,但看起来 Reflector 使用您对 Current 调用所做的操作作为信号。

验证

我将 While 方法更改为:

public static void While(List<int> x)
{        
    using (var enumerator = x.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            int item = enumerator.Current;
            Console.WriteLine(item);
        }
    }
}

现在即使使用 csc/o-/debug+,Reflector 仍认为 while 循环实际上是一个 foreach 循环。

关于c# - 为什么反编译代码包含 foreach 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34678362/

相关文章:

haskell - 将 haskell 代码概括/编译为 lambda

ios - 如何反编译iOS应用程序?

ocaml - 反编译 OCaml 字节码文件

c# - Windows 8.1 如何修复这个过时的代码?

c# - 如果 MSDTC 被禁用,您如何绕过 TransactionScope 内的多个数据库连接?

c# - 实体做得太多?

c - 可以反编译用 C 编写的 DLL 吗?

java - 如何读取 .class 文件的完全限定名称

c# - 为什么我的 BackgroundService 立即停止?

c# - 防止自动命名空间前缀