.NET 中的“闭包"是什么? [英] What are 'closures' in .NET?

查看:30
本文介绍了.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 中的“闭包"是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆