我正在学习 C#。我的意思是闭包吗 a construct that can adopt the changes in the environment in which it is defined.
例子 :
List<Person> gurus =
new List<Person>()
{
new Person{id=1,Name="Jon Skeet"},
new Person{id=2,Name="Marc Gravell"},
new Person{id=3,Name="Lasse"}
};
void FindPersonByID(int id)
{
gurus.FindAll(delegate(Person x) { return x.id == id; });
}
该变量id
在 FindPersonByID() 的范围内声明,但我们仍然可以访问id
匿名函数内的局部变量(即)delegate(Person x) { return x.id == id; }
(1) 我对闭包的理解是否正确?
(2) 我们可以从闭包中获得什么优势?