你能解释一下 lambda 表达式吗? [英] Can you explain lambda expressions?

查看:28
本文介绍了你能解释一下 lambda 表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的get lambda 表达式.虽然它们从 ALGOL 时代就已经存在,但直到最近 Python 和 Ruby 变得非常流行时,我才开始听说它们.现在 C# 具有 => 语法,我的世界 (.NET) 中的人们越来越多地谈论 lamdba 表达式.

I don't really get lambda expressions. While they've been around since the days of ALGOL, I didn't start hearing about them until fairly recently, when Python and Ruby became very popular. Now that C# has the => syntax, people in my world (.NET) are talking about lamdba expressions more and more.

我已经阅读了关于 lambda 演算的维基百科文章,但我并不是真正的数学专家.从实际的角度,我真的不太理解.我什么时候会使用 lambda 表达式?为什么?我怎么知道这是我应该做的?

I've read the Wikipedia article on the lambda calculus, but I'm not really a math guy. I don't really understand it from a practical perspective. When would I use lambda expressions? Why? How would I know that it's what I should be doing?

您能否以前后格式展示如何解决 lambda 表达式问题的示例?任何命令式语言都可以,但 C# 对我来说最容易理解.

Can you show examples of how you would solve problems with lambda expressions, in a before-and-after format? Any imperative language is fine, but C# would be easiest for me to understand.

推荐答案

基本上就 C# 而言,Lambda 表达式是创建委托(或表达式树,但让我们暂时搁置这些)的一种简单方法.

Basically as far as C# is concerned, lambda expressions are an easy way to create a delegate (or an expression tree, but let's leave those aside for now).

在 C# 1 中,我们只能从普通方法创建委托实例.在 C# 2 中,我们获得了匿名方法.在 C# 3 中,我们获得了 lambda 表达式,它们就像更简洁的匿名方法.

In C# 1 we could only create delegate instances from normal methods. In C# 2 we gained anonymous methods. In C# 3 we gained lambda expressions, which are like more concise anonymous methods.

当你想表达一些接受一个值并返回一个值的逻辑时,它们特别简洁.例如,在 LINQ 的上下文中:

They're particularly concise when you want to express some logic which takes one value and returns a value. For instance, in the context of LINQ:

                       // Only include children - a predicate
var query = dataSource.Where(person => person.Age < 18) 
                       // Transform to sequence of names - a projection
                      .Select(person => person.Name);

我关于闭包的文章.

这篇关于你能解释一下 lambda 表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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