是 C# 闭包中的 Lambda 表达式吗? [英] Are Lambda expressions in C# closures?

查看:25
本文介绍了是 C# 闭包中的 Lambda 表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lambda 表达式(以及在某种程度上,匿名函数)是闭包吗?

Are lambda expressions (and to a degree, anonymous functions) closures?

我对闭包的理解是,它们是被视为对象的函数,这似乎是对匿名函数和 Lambda 表达式功能的准确表示.

My understanding of closures are that they are functions that are treated as objects, which seems to be an accurate representation of what anonymous functions and Lambda expressions do.

将它们称为闭包是否正确?我知道闭包是由于 lisp 方言而出现(或变得流行),但这也是一个通用的编程术语吗?

And is it correct to call them closures? I understand that closures came about (or became popular) due to the lisp dialect, but is it also a general programming term?

感谢您提供的任何说明!

Thanks for any clarification that you can provide!

推荐答案

lambda 可以使用闭包实现,但它本身不一定是闭包.

A lambda may be implemented using a closure, but it is not itself necessarily a closure.

闭包-该函数的局部变量.".

A closure is "a function together with a referencing environment for the non-local variables of that function.".

当您创建使用在方法外部定义的变量的 lambda 表达式时,必须使用闭包来实现 lambda.例如:

When you make a lambda expression that uses variables defined outside of the method, then the lambda must be implemented using a closure. For example:

int i = 42;

Action lambda = () => { Console.WriteLine(i); }; 

在这种情况下,编译器生成的方法必须能够访问在完全不同的范围内定义的变量 (i).为了让它起作用,它生成的方法是一个函数和引用环境"——基本上,它创建了一个闭包"来检索对变量的访问.

In this case, the compiler generated method must have access to the variable (i) defined in a completely different scope. In order for this to work, the method it generates is a "function together with the referencing environment" - basically, it's creating a "closure" to retrieve access to the variable.

然而,这个 lambda:

However, this lambda:

Action lambda2 = () => { Console.WriteLine("Foo"); }

不依赖于任何引用环境",因为它是一个完全包含的方法.在这种情况下,编译器生成一个普通的静态方法,完全不涉及闭包.

does not rely on any "referencing environment", since it's a fully contained method. In this case, the compiler generates a normal static method, and there is no closure involved at all.

在这两种情况下,lambda 都在创建一个 delegate(函数对象"),但它只在第一种情况下创建一个闭包,因为 lambda 不一定需要捕获"所有情况下的引用环境.

In both cases, the lambda is creating a delegate ("function object"), but it's only creating a closure in the first case, as the lambda doesn't necessarily need to "capture" the referencing environment in all cases.

这篇关于是 C# 闭包中的 Lambda 表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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