什么是闭包?我们在 .NET 中有它们吗?
What is a closure? Do we have them in .NET?
如果它们确实存在于 .NET 中,您能否提供一个代码片段(最好是 C#)来解释它?
If they do exist in .NET, could you please provide a code snippet (preferably in C#) explaining it?
推荐答案我有一篇关于这个的文章很有话题.(它有很多例子.)
I have an article on this very topic. (It has lots of examples.)
本质上,闭包是一个代码块,可以在以后执行,但是它维护了它第一次创建的环境——即它仍然可以使用创建它的方法的局部变量等,即使在该方法完成执行之后.
In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing.
闭包的一般特性是通过匿名方法和 lambda 表达式在 C# 中实现的.
The general feature of closures is implemented in C# by anonymous methods and lambda expressions.
以下是使用匿名方法的示例:
Here's an example using an anonymous method:
using System; class Test { static void Main() { Action action = CreateAction(); action(); action(); } static Action CreateAction() { int counter = 0; return delegate { // Yes, it could be done in one statement; // but it is clearer like this. counter++; Console.WriteLine("counter={0}", counter); }; } }输出:
counter=1 counter=2这里我们可以看到 CreateAction 返回的 action 仍然可以访问 counter 变量,并且确实可以增加它,即使 CreateAction 本身已经完成.
Here we can see that the action returned by CreateAction still has access to the counter variable, and can indeed increment it, even though CreateAction itself has finished.
更多推荐
.NET 中的“闭包"是什么?
发布评论