from WIKI:"In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function" 函数+自由变量
Closures may be defined as a set of behaviour or instructions that are encapsulated as an object such that it could be sent to other object yet can hold the context of the caller. In other words, a closures are special object that are encapsulated into an object but can hold the context of the caller.
本质上是一个函数里面创建的局部变量,不仅在函数里面可以使用,而且还可以在函数外使用,并且一直保留最新的值
c#中用Lambda/匿名表达式实现,
相当于T1是一个类,而返回的匿名对象result则是T1的一个属性.
如果这个匿名函数会被返回给其他对象调用,那么编译器会自动将匿名函数所用到的方法T1中的局部变量的生命周转期自动提升并与匿名函数的生命周期相同,这样就称之为闭合.
闭包经常用于创建含有隐藏数据的函数
public class TClosue
{ public Func<int> T1(int i) { int n = 999; Func<int> result = () => { n++; Console.WriteLine(n); return n; }; n = 10; return result; } }
var a = new TClosue(); var b = a.T1(2); Console.WriteLine(b());// 输出n=11; Console.WriteLine(b());//输出n=12;