首先要理解Lambda表达式的延迟执行(Deferred execution)
An important feature of most query operators is that they execute not when
constructed, but when enumerated.
其次来理解捕获迭代变量
When you capture iteration variables in for and foreach statements, C# treats those
iteration variables as though they were declared outside the loop。
Action[] actions = new Action[3];
for (int i = 0; i < 3; i++)
actions [i] = () => Console.Write (i); // 用Lambda表达式来实例化Action委托。//这样的代码基本上就是一个Bug。
foreach (Action a in actions) a(); // 333。执行。
最后需要理解这样的外部变量的生命周期扩展到了相应的委托。
int seed = 0;
Func<int> natural = () => seed++;
Console.WriteLine (natural()); // 0
Console.WriteLine (natural()); // 1
Console.WriteLine (seed); // 2