int[] data = new int[] { 1, 2, 3, 4, 5 };
List<Func<int>> actions = new List<Func<int>>();
foreach (int x in data)
{
actions.Add(() => x);
}
foreach (var foo in actions)
{
Console.WriteLine(foo());
}
如果你使用的是C# 4.0,运行结果是55555。
不要感到吃惊,因为在 C# 4.0 中,foreach的实现是这样的:
C# code
int[] data = new int[] { 1, 2, 3, 4, 5 };
List<Func<int>> actions = new List<Func<int>>();
IEnumerator e = data.GetEnumerator();
int x = 0;
while (e.MoveNext())
{
x = (int)e.Current;
actions.Add(() => x);
}
foreach (var foo in actions)
{
Console.WriteLine(foo());
}
int[] data = new int[] { 1, 2, 3, 4, 5 };
List<Func<int>> actions = new List<Func<int>>();
IEnumerator e = data.GetEnumerator();
while (e.MoveNext())
{
int x = 0;
x = (int)e.Current;
actions.Add(() => x);
}
foreach (var foo in actions)
{
Console.WriteLine(foo());
}
------解决方案-------------------- Closure is very useful in JavsScript, but for C#... I've never met any situation where I use it.
------解决方案-------------------- 这样会养成不良的编程习惯
从概念上理解(() => x);将编译成一个方法,而x的内存地址被固定了。 foreach (var foo in actions)里面应该始终会被调用成一个返回值。