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

本文关键字:包含 foreach 循环 代码 编译 为什么 | 更新日期: 2023-09-27 18:29:40

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

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

让反编译器判断前一个代码块是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循环。这里有一个例子。

我自己也想看到这一点,写了一个带有foreach循环的小程序并进行了编译。然后我使用了一个分解器来查看代码的样子。我没想到会有一个前臂环,但当我真的得到一个时,我很惊讶。

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

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

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

以下是我编译的代码,它使我们更容易了解差异:

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编译

在这种情况下,反射器9.0.1.318可以区分。。。I也是。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。。。而在CCD_ 8中则相反。

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

在这种情况下,Reflector在两种情况下都显示出while环路,并且IL实际上相同的。两个循环中都没有stloc.1/ldloc.1对。

您的IL

再看看编译所产生的IL,foreach循环中的Current属性有一对stloc.1/ldloc.1

手工制作的IL

我从"无法区分版本"中提取IL,只是更改了.locals部分,并将stloc.1/ldloc.1添加到混合物中,宾果反射镜认为这又是一个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帮助我理解了其中的差异。他提到了要点,但用了一种"更详细的方式",所以对于未来的潜在读者,我想用不同的语言来表达。

未优化时,foreach循环内部由(最多)三个变量组成。

  • 枚举器是迭代所必需的
  • bool变量,用于判断MoveNext的调用返回true还是false
  • 以及存储当前值的int变量
.locals init([0]int32,[1] valuetype[msorlib]System.Collections.Generic.List`1/枚举器,[2] bool)

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

相反,while循环没有int变量。

.locals init([0]valuetype[msorlib]System.Collections.Generic.List`1/枚举器,[1] bool)

反编译器使用这个额外的int变量来表示带有foreach循环的代码。这可以通过在while循环中添加该变量来验证,如Jon Skeet所示。

int item = enumerator.Current;

当反编译相应的IL代码时,反编译器会显示foreach循环,其中实际使用了while循环。

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

stloc.1
ldloc.1

在优化代码时,它们都可以删除。因此,当两个变量都被删除而int变量不存在时,反编译器会用while循环表示IL。

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