class Program
{
static void Main(string[] args)
{
Action<int> TestCreateInstance()
{
int count = 0;
Action<int> action = delegate (int number)
{
count += number;
Console.WriteLine(count);
};
action(1);
return action;
}
Action<int> act = TestCreateInstance();
act(10);
act(100);
act(1000);
Console.ReadKey();
}
}
这段代码运行后得到的结果是
1
11
111
1111
你们可能看不懂,可以在VS中断点运行以下。
这是因为编译器在处理匿名方法时是创建一个类来保管匿名方法,同时匿名方法中的局部变量作为类的字段进行设置。所以这里面的count并没有随着方法的用完而销毁,它是作为类的字段存在堆中的。