问题描述
我在果壳重读从C#5.0的一部分对捕获迭代变量(第138页),我试图波纹管重现C#4.0和C#5.0,但不抱希望的代码来捕获到现在为止的区别
I'm rereading a part from c# 5.0 in Nutshell about the capturing iteration variables (Page 138) and I have tried to reproduce the code bellow on c# 4.0 and c# 5.0 but with no hope to catch the difference until now
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#编译器
Updateto explain more the issue the output with c# 4.0 will be different from c# 5.0
I Know this may be less useful due to update to a recent version of C# Compiler
任何人都可以见识一下如何重现这个问题?
can anyone enlighten me on how to reproduce this issue ?
推荐答案
您不能因为你改变了版本的.NET Framework,但不包括编译器重现它。你总是使用C#5.0版,修正了问题的的foreach
循环。你可以看到为
的问题,但循环:
You can't reproduce it because you are changing the version of the .Net framework but not the compiler. You're always using C# v5.0 which fixes the issue for foreach
loops. You can see the issue with for
loops though:
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中(我做了局部)。
To use the old compiler you need an old VS version. In this case to see your code break with foreach
you need to test it in VS 2010 (I did locally).
您可能想尝试改变编译器的语言版本(如萨那托斯在评论建议),但不使用旧的编译器。它使用相同的编译器,但限制你使用特定功能:
You might want to try to change the language version of the compiler (as xanatos suggested in the comments) but that doesn't use an old compiler. It uses the same compiler but limits you to using specific features:
由于C#编译器的每个版本包含扩展的语言规范, / langversion
不给你的编译器的早期版本的等效功能。
通过
这篇关于重现捕获迭代变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!