关闭是什么特别? [英] What is so special about closures?

查看:125
本文介绍了关闭是什么特别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读这篇文章关于关闭的文章,其中他们说:


  • 所有管道是自动的

  • 编译器创建一个包装器类和延长变量的生命周期

  • .NET编译器会为你管理管道等。

所以我根据他们的代码做了一个例子,它看起来好像闭包只是类似于常规命名的方法,也照顾局部变量没有担心,其中所有的管道是自动的。

So I made an example based on their code and to me, it seems as though closures just act similarly to regular named methods which also "take care of the local variables without worry" and in which "all the plumbing is automatic".

这种局部变量的包装解决了什么问题,使得闭包变得如此特别/有趣/有用?
$ b

Or what problem did this "wrapping of local variables" solve that makes closures so special / interesting / useful?

using System;
namespace TestingLambda2872
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int> AddToIt = AddToItClosure();

            Console.WriteLine("the result is {0}", AddToIt(3)); //returns 30
            Console.ReadLine();
        }

        public static Func<int, int> AddToItClosure()
        {
            int a = 27;
            Func<int, int> func = s => s + a;
            return func;
        }
    }
}



答案



因此,这个问题的答案是阅读 Jon Skeet的文章关闭,Marc指出。这篇文章不仅展示了在C#中导致lambda表达式的演变,而且展示了Java中如何处理闭包,这是一个很好的阅读本主题。

Answer

So the answer to this one is to read Jon Skeet's article on closures that Marc pointed out. This article not only shows the evolution leading up to lambda expressions in C# but also shows how closures are dealt with in Java, an excellent read for this topic.

推荐答案

您的示例不清楚,并且没有(IMO)显示典型的捕获用法(捕获的唯一的事情是 a ,总是3 ,所以不是很有趣)。

Your example isn't clear, and doesn't (IMO) show typical capture usage (the only thing captured is a, which is always 3, so not very interesting).

考虑这个教科书的例子(一个谓语):

Consider this text-book example (a predicate):

List<Person> people = ...
string nameToFind = ...
Person found = people.Find(person => person.Name == nameToFind);

你需要做更多的工作,即使我们是懒惰:

Now try it without a closure; you need to do a lot more work, even if we are lazy:

PersonFinder finder = new PersonFinder();
finder.nameToFind = ...
Person found = people.Find(finder.IsMatch);
...
class PersonFinder {
    public string nameToFind; // a public field to mirror the C# capture
    public bool IsMatch(Person person) {
        return person.Name == nameToFind;
    }
}

捕获方法进一步扩展到很多不同的变量

The capture approach extends further to lots of variables at different scopes - a lot of complexity that is hidden.

除了名称之外,上面是C#编译器在后面的一个近似值场景。注意,当涉及额外的范围时,我们开始链接不同的捕获类(即内部范围具有对外部范围的捕获类的引用)。非常复杂。

Other than the names, the above is an approximation of what the C# compiler does behind the scenes. Note that when additional scopes are involved we start chaining the different capture classes (i.e. inner scopes have a reference to the capture class of outer scopes). Quite complex.

Jon Skeet有一个很好的在这里的文章,以及在他的书中更多

Jon Skeet has a good article on this here, and more in his book.

这篇关于关闭是什么特别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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