重现捕获迭代变量问题

Reproduce Capturing iteration variable issue

我正在重读 C# 5.0 in Nutshell 中关于捕获迭代变量的部分(第 138 页),我试图在 C# 4.0 和 C# 5.0 上重现下面的代码,但直到现在才希望能发现差异

using System;
class Test
{
    static void Main()
    {      
        Action[] actions = new Action[3];
        int i = 0;
        foreach (char c in "abc")
            actions[i++] = () => Console.Write(c);
        for (int j = 0; j < 3; j++)
        {
            actions[j]();
        }
        foreach (Action a in actions) a();    
        Console.ReadLine(); 
    }
}

注意 我有 Visual studio 2012(安装了 .net 4.0 和 4.5),我在尝试重现问题时更改了目标框架

更新 进一步解释 c# 4.0 的输出与 c# 5.0
不同的问题 我知道由于更新到最新版本的 C# 编译器,这可能不太有用

谁能告诉我如何重现这个问题?

自 4.0 以来,此行为已针对 foreach 循环进行了更改。但是您可以使用 for 循环重现它:

static void Main()
{      
    Action[] actions = new Action[3];
    int i = 0;
    for (var c = 0; c < 3; c++)
        actions[i++] = () => Console.Write(c);
    for (int j = 0; j < 3; j++)
    {
        actions[j]();
    }
    foreach (Action a in actions) a();    
    Console.ReadLine(); 
}

输出:“333333”

您无法重现它,因为您更改的是 .Net 框架的版本,而不是编译器。您一直在使用 C# v5.0,它修复了 foreach 循环的问题。你可以看到 for 循环的问题:

Action[] actions = new Action[3];
int i = 0;

for (int j = 0; j < "abc".Length; j++)
    actions[i++] = () => Console.Write("abc"[j]);
for (int j = 0; j < 3; j++)
{
    actions[j]();
}
foreach (Action a in actions) a();
Console.ReadLine();

要使用旧版编译器,您需要旧版 VS。在这种情况下,要看到您的代码因 foreach 而中断,您需要在 VS 2010 中对其进行测试(我在本地进行)。


您可能想尝试更改编译器的语言版本(如 xanatos 在评论中所建议的那样),但这不使用旧的编译器。它使用相同的编译器,但限制您使用特定功能:

Because each version of the C# compiler contains extensions to the language specification, /langversion does not give you the equivalent functionality of an earlier version of the compiler.

来自/langversion (C# Compiler Options)

因为此问题已在 C# 编译器 5.0 中修复,您无法使用 Visual studio 2012 重现此问题。

您需要使用 C# 编译器 4.0 版才能重现作者试图解释的问题。使用 Visual studio 2010 可以重现该问题。

即使你在Vs2012里改了Language版本,还是不行。因为 you're still using the C# 5.0 compiler.