public void T12D6() { ClosureDelegate test = CreateDelegateInstance(); test(); Console.ReadKey(); }
//模拟的Main方法 public void Main() { ClosureDelegate one = DoClosureDelegateInstance(); one(); /* * 进行do...方法时会先调用two委托实例,方法执行完毕后count变量应该会被销毁.但是还有匿名对象的引用。所以 * 它的生命周期被延长。 */ }
private static void Mathod() { string outVariable = "外部变量"; string capturedVarible = "被捕获的外部变量"; ClosureDelegate cosure = delegate { string localvariable = "匿名方法局部变量"; Console.WriteLine(capturedVarible + " " + localvariable); }; cosure(); }
private static ClosureDelegate CreateDelegateInstance() { int count = 1; ClosureDelegate closuredelegate = delegate { Console.WriteLine(count); count++; }; closuredelegate(); return(closuredelegate); }
//闭包延长变量的生命周期 private static ClosureDelegate DoClosureDelegateInstance() { //这里定义了外部变量 int count = 1; ClosureDelegate two = () => {//匿名方法 Console.WriteLine(count); count++; }; //调用委托 two(); return(two); }
static void Main(string[] args) { ClosureDelegate test = CreateDelegateInstance(); // 此时会回调匿名方法输出count的值 test(); /* * 1 * 2 */ Console.Read(); }
// 闭包延长变量的生命周期 private static ClosureDelegate CreateDelegateInstance() { // 外部变量 int count = 1; ClosureDelegate closuredelegate = delegate { Console.WriteLine(count); // 捕捉了外部变量 count++; }; // 调用委托 closuredelegate(); return(closuredelegate); }
// 闭包方法 private static void closureMethod() { // outVariable和capturedVariable对于匿名方法而言都是外部变量 string outVariable = "外部变量"; // 而capturedVariable是被匿名方法捕获的外部变量 string capturedVariable = "被捕获的外部变量"; ClosureDelegate closuredelegate = delegate { // localvariable是匿名方法中局部变量 string localvariable = "匿名方法局部变量"; // 引用capturedVariable变量 Console.WriteLine(capturedVariable + " " + localvariable); }; // 调用委托 closuredelegate(); }