表达和Func键的区别 [英] difference between Expression and Func

查看:103
本文介绍了表达和Func键的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么表情和Func键之间的区别?相同的任务可以由两个来实现。那么有什么区别?

What is the difference between Expression and Func? The same task can be attained by both. So what is the difference?

推荐答案

表达式树是的数据的逻辑表示 - 这意味着它们可以在执行时由之类的东西LINQ提供程序进行审查。他们可以制定出代码的含义,并可能将其转换成另一种形式,如SQL。

Expression trees are data representations of logic - which means they can be examined at execution time by things like LINQ providers. They can work out what the code means, and possibly convert it into another form, such as SQL.

函数功能家庭类型,然而,仅仅代表。他们最终成为正常的IL,可直接执行的,但不(容易)检查。请注意,您可以编译表达式树(当然,表达式来; T> LambdaExpression )为代表和执行这些内部管理代码为好,如果你需要。

The Func family of types, however, are just delegates. They end up as normal IL, which can be executed directly, but not (easily) examined. Note that you can compile expression trees (well, Expression<T> and LambdaExpression) into delegates and execute those within managed code as well, if you need to.

您可以建立表达式树使用表达式类的工厂方法手动,但通常你只需要使用一个事实,即C#能转换的 lambda表达式的到两个表达式树和正常的代表:

You can build up expression trees manually using the factory methods in the Expression class, but usually you just use the fact that C# can convert lambda expressions into both expression trees and normal delegates:

Expression<Func<int, int>> square = x => x * x;
Func<int, int> square = x => x * x;

请注意,有在其上lambda表达式可以被转换成表达式树的限制。最重要的是,仅由单个表达式(而不是语句体)的lambda表达式可以转换:

Note that there are limitations on which lambda expressions can be converted into expression trees. Most importantly, only lambdas consisting of a single expression (rather than a statement body) can be converted:

// Compile-time error
Expression<Func<int, int>> square = x => { return x * x; };
// Works fine
Func<int, int> square = x => { return x * x; };

这篇关于表达和Func键的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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