【发布时间】:2015-12-16 17:56:03
【问题描述】:
使用 Visual Studio 2013,我试图重现 Eric Lippert 的博文 "Closing over the loop variable considered harmful" 中提到的问题。
在项目属性中,我选择“C# 3.0”作为语言版本(Build > Advanced…)。此外,我选择“.NET Framework 3.5”作为目标框架,好像我认为这不是必需的,因为这仅涉及语言。
运行他的代码:
using System;
using System.Collections.Generic;
namespace Project1
{
class Class1
{
public static void Main(string[] args)
{
var values = new List<int>() { 100, 110, 120 };
var funcs = new List<Func<int>>();
foreach (var v in values)
{
funcs.Add(() => v);
}
foreach (var f in funcs)
Console.WriteLine(f());
}
}
}
预期输出:
120 120 120实际输出:
100 110 120正如Eric Lippert himself 在"Is there a reason for C#'s reuse of the variable in a foreach?" 中的回答:
for循环不会更改,更改不会“向后移植”到以前的 C# 版本。因此,您在使用此成语时应继续小心。
我做错了什么?
【问题讨论】:
标签: c# visual-studio visual-studio-2013