C# - 关闭 - 澄清
我正在学习 C#。我可以将闭包理解为一个可以采用定义它的环境中的更改的构造吗?
示例:
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)闭包能给我们带来什么好处?
I am learning C#.Can I mean closure as a construct that can adopt the changes in the environment in which it is defined.
Example :
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; });
}
The variable id
is declared in the scope of FindPersonByID() but t we still can access
the local variable id
inside the anonymous function (i.e) delegate(Person x) { return x.id == id; }
(1) Is my understanding of closure is correct ?
(2) What are the advantages can we get from closures?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,
FindPersonByID
内部的代码通过在 lambda 表达式中使用参数id
来利用闭包。严格来说,闭包的定义有点复杂,但在基本层面上这是正确的。如果您想了解有关它们如何运作的更多信息,我鼓励您阅读以下文章闭包的主要优点本质上就是您上面所演示的。它允许您以更自然、直接的方式编写代码,而不必担心如何生成 lambda 表达式的实现细节(通常)
考虑例如在没有闭包的情况下您需要编写多少代码
All这只是为了表达在委托内部使用参数的概念。
Yes the code inside of
FindPersonByID
is taking advantage of a closure by using the parameterid
within the lambda expression. Strictly speaking the definitions of closures are a bit more complex but at a basic level this is correct. If you want more information on how they function I encourage you to read the following articlesThe primary advantage of closures is essentially what you demonstrated above. It allows you to write the code in a more natural, straight forward fashion without having to worry about the implementation details of how the lambda expression is generated (generally)
Consider for example how much code you would have to write in the abscence of closures
All of this just to express the concept of using a parameter inside of a delegate.