01.定义闭包其实就是使用的变量已经脱离其作用域,却由于和作用域存在上下文关系 从而可以在当前环境中继续使用其上文环境中所定义的一种函数对象。 using System; using System.Collect
01.定义闭包其实就是使用的变量已经脱离其作用域,却由于和作用域存在上下文关系
从而可以在当前环境中继续使用其上文环境中所定义的一种函数对象。
using System;
using System.Collections.Generic;
using static System.Console;
namespace Init
{
class Program
{
static void Main(string[] args)
{
var a=new TCloser();
var b = a.T1();
//委托b中仍然能调用n
//匿名委托b是允许使用它所在的函数或者类里面的局部变量
WriteLine(b());
ReadKey();
}
}
class TCloser
{
public Func<int> T1()
{
//n实际上是属于函数T1的局部变量
//生命周期应该是伴随着函数T1的调用结束而被释放掉的
var n = 99;
return () =>
{
WriteLine(n);
return n;
};
}
}
}
变量n实际上是属于函数T1的局部变量,它本来生命周期应该是伴随着函数T1的调用结束而被释放掉的,但这里我们却在返回的委托b中仍然能调用它,这里正是闭包所展示出来的威力。因为T1调用返回的匿名委托的代码片段中我们用到了n,而在编译器看来,这些都是合法的,因为返回的委托b和函数T1存在上下文关系,也就是说匿名委托b是允许使用它所在的函数或者类里面的局部变量的,于是编译器通过一系列动作(具体动作我们后面再说)使b中调用的函数T1的局部变量自动闭合,从而使该局部变量满足新的作用范围。
02.
Lambda表达式捕捉变量使用的是最新的值
Action myAction = null;
for (int i = 0; i < 5; i++)
{
myAction += () =>
{
//内层函数引用外层函数的变量不是会随外层函数变量的变化而变化的,只会引用外层函数的变量的最终值。
//由于Lambda表达式调用了该变量i,此处会将i提升为一个字段,既是 public int i ,字段i最后取值为5
WriteLine(i);
};
}
myAction();//5555
相当于
class Program
{
public int a = 5;
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Action action = delegate { WriteLine(new Program().a); };
action.Invoke();//5555
}
ReadKey();
}
}
改进方法
Action myAction = null;
for (int i = 0; i < 5; i++)
{
int a = i;
myAction += () =>
{
//由于Lambda表达式调用了该变量i,此处会将i提升为一个字段,该字段最后取值为5
//或使用以下方式:
WriteLine(a);//01234
};
}
myAction();
03.循环变量下的委托
class Program
{
static void Main(string[] args)
{
var items = new string[] { "one", "two", "three" };
var actions = new List<Action>();
foreach (var item in items)
{
actions.Add(() => WriteLine(item.ToString()));
}
foreach (var item in actions)
{
item.Invoke(); //one two three
}
ReadKey();
}
}