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

Why does decompiled code contain a foreach-loop?

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

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

允许反编译器判断前一个代码块是 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[=12=]00
.try
{
    IL_001e: br.s IL_002e
    // loop start (head: IL_002e)
        IL_0020: ldloca.s CS[=12=]00
        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[=12=]00
        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[=12=]00
    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 循环应该 "hide the complexity of the enumerators"。 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 - 同样,Currentstloc.1/ldloc.1 对属性 在 foreach 循环中。

Hand-crafted IL

我从 "can't tell the difference version" 中获取了 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 循环。

Jon Skeet 帮助我理解了其中的区别。他提到了关键点,但是在 'bit more elaborated way' 中,所以对于未来潜在的读者,我想用不同的词来表达。

当non-optimized时,一个foreach-loop内部包含(最多)三个变量。

  • 迭代所必需的枚举器,
  • 一个布尔变量,用于判断 MoveNext 的调用是返回真还是假,
  • 和一个存储当前值的 int 变量。
.locals init (
    [0] int32,
    [1] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator,
    [2] bool
)

请注意,并非所有编译器版本都生成 bool 变量。该代码可能仅由枚举器和 int 变量组成。

相比之下,while-loop 没有那个 int 变量。

.locals init (
    [0] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator,
    [1] bool
)

反编译器使用这个额外的 int 变量来表示带有 foreach-loop 的代码。这可以通过在 while-loop.

中添加该变量来验证,如 Jon Skeet 所示
int item = enumerator.Current;

反编译相应的 IL 代码时,反编译器显示 foreach-loop,而实际使用的是 while-loop。

然而,int 和 bool 变量都不是必需的。在 IL 代码中,您可以看到两个值都从堆栈中提取到一个变量中,然后立即再次压入堆栈。

stloc.1
ldloc.1

在优化代码时,它们都可以去掉。因此,当两个变量都被删除并且 int 变量不存在时,反编译器用 while-loop.

表示 IL

也就是说,并非所有编译器版本都删除了 int 变量。旧版本只删除了 bool 变量,因此,反编译器可以在两个循环之间产生差异。