.NET中的“闭包”是什么? [英] What are 'closures' in .NET?
问题描述
什么是关闭?
如果它们存在于.NET中,你能否提供一个代码片段(最好是在C# )解释它?
编辑:我经历了 Jon Skeet的文章来了解什么是闭包,以及如何在.NET中使用它们。
我有一篇关于这个话题的文章。 (它有很多例子。)
实质上,闭包是一个代码块,可以在稍后的时间执行,但维护环境第一次创建 - 即使它已经完成执行,它仍然可以使用创建它的方法的局部变量等。
闭包的一般特性
这是一个使用匿名方法的示例: using System;
class Test
{
static void Main()
{
Action action = CreateAction();
action();
action();
}
static Action CreateAction()
{
int counter = 0;
return delegate
{
//是的,它可以在一个语句中完成;
//但是它更清晰这样。
counter ++;
Console.WriteLine(counter = {0},counter);
};
}
}
输出:
counter = 1
counter = 2
$ b b
在这里我们可以看到,CreateAction返回的动作仍然可以访问计数器变量,并且确实可以增加它,即使CreateAction本身已经完成。
What is a closure? Do we have them in .NET?
If they do exist in .NET, could you please provide a code snippet (preferably in C#) explaining it?
EDIT: I went through Jon Skeet's article to understand what closures are and how to use them in .NET.
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.
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);
};
}
}
Output:
counter=1
counter=2
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中的“闭包”是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!