方法内声明的局部变量的生命周期仅限于执行该方法。 但是在下面的代码示例中,在执行方法之后保留了局部变量索引的生命周期。
class Program
{
static Action action;
static void Main(string[] args)
{
setAction();
for (int i = 0; i < 5; i++)
{
action();
}
Console.ReadLine();
}
static void setAction()
{
var index = 5;
action = () => {
index++;
Console.WriteLine("Value in index is {0}",index);
};
}
}
程序的输出是这个
Value in index is 6
Value in index is 7
Value in index is 8
Value in index is 9
Value in index is 10
我无法理解如何保留变量索引中的值。