C# Lambda 表达式:我为什么要使用它们? [英] C# Lambda expressions: Why should I use them?

查看:29
本文介绍了C# Lambda 表达式:我为什么要使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经快速阅读了 Microsoft Lambda 表达式 文档.

I have quickly read over the Microsoft Lambda Expression documentation.

不过,这种例子帮助我更好地理解:

This kind of example has helped me to understand better, though:

delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

不过,我不明白为什么这是一项创新.它只是一个在方法变量"结束时死亡的方法,对吗?为什么我要使用这个而不是真正的方法?

Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?

推荐答案

Lambda 表达式 是匿名委托的一种更简单的语法,可以在任何可以使用匿名委托的地方使用.然而,事实并非如此.lambda 表达式可以转换为表达式树,这允许像 LINQ to SQL 这样的很多魔法.

Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.

以下是一个 LINQ to Objects 表达式的示例,使用匿名委托,然后是 lambda 表达式,以显示它们在眼睛上有多容易:

The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:

// anonymous delegate
var evens = Enumerable
                .Range(1, 100)
                .Where(delegate(int x) { return (x % 2) == 0; })
                .ToList();

// lambda expression
var evens = Enumerable
                .Range(1, 100)
                .Where(x => (x % 2) == 0)
                .ToList();

Lambda 表达式和匿名委托比编写单独的函数有优势:它们实现了闭包 允许您将本地状态传递给函数而无需添加参数函数或创建一次性使用的对象.

Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects.

表达式树 是一项非常强大的新功能C# 3.0 允许 API 查看表达式的结构,而不仅仅是获取对可以执行的方法的引用.API 只需将委托参数转换为 Expression 参数,编译器将从 lambda 生成表达式树,而不是匿名委托:

Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:

void Example(Predicate<int> aDelegate);

称为:

Example(x => x > 5);

变成:

void Example(Expression<Predicate<int>> expressionTree);

后者将获得描述表达式 抽象语法树> x >5.LINQ to SQL 依靠这种行为能够将 C# 表达式转换为服务器端过滤/排序等所需的 SQL 表达式.

The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.

这篇关于C# Lambda 表达式:我为什么要使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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