.NET 中的“闭包"是什么?

编程入门 行业动态 更新时间:2024-10-17 21:26:15
本文介绍了.NET 中的“闭包"是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

什么是闭包?我们在 .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 中的“闭包"是什么?

本文发布于:2023-11-02 14:12:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!