表达树的优点 [英] advantage of Expression Trees

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

问题描述

我完全无法理解表达式树的用途。为什么我们应该去表达树。我们可以直接执行lambda表达式。为什么我们应该将lambda表达式赋给表达式树来执行。

Ex



I am exactly unable to understand what is the use of expression tree.why should we go for expression tree.we can directly execute lambda expression.why should we assign lambda expression to the expression tree to execte.
Ex

Lamda expression
Func<int, int, int> function = (a,b) = > a + b;

This delegate is compiled into executable code in your application
Console.WriteLine("deleg2(4) = {0}", function (4,5))







Expression<Func<int, int, int>> expression = (a,b) => a + b;
Func<int, int, int> expression = expr.Compile();
Console.WriteLine("deleg2(4) = {0}", expression (4,5));

推荐答案

在C#程序中不执行LINQ to SQL查询。相反,它被翻译成SQL查询,通过电线发送,并在数据库服务器上执行。

换句话说,以下代码永远不会在您的程序中实际执行:

A LINQ to SQL query is not executed inside your C# program. Instead, it is translated into SQL query, sent across a wire, and executed on a database server.
In other words, the following code is never actually executed inside your program:
var query = from c in db.Customers
            where c.City == "Nantes"
            select new { c.City, c.CompanyName };



首先将其翻译成以下SQL语句,然后在服务器上执行:


It is first translated into the following SQL statement and then executed on a server:

SELECT [t0].[City], [t0].[CompanyName]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[City] = @p0



将表达式树等数据结构转换为SQL显然要比将原始IL或可执行代码转换为SQL要容易得多。



表达式树也用在动态语言运行库(DLR)中,以提供动态语言和.NET Framework之间的互操作性,并使编译器编写器能够发出表达式树而不是微软中间语言(MSIL) 。



为了更好地理解,请参考以下链接:

表达式树[ ^ ]





我真的不明白你的问题,但我知道你想说什么:为什么在你可以直接使用lambda表达式时使用Func类?



简单回答 - 例如,你想在代码中使用一些lambda表达式,所以你需要多次写入它。如果您使用Func或Action类,则只需调用此类实例并完成。第二个原因是当你想将一些lambda表达式传递给方法时 - 它也是由Action或Func等代表完成的。



最好的问候

PZ
Hi,

I don't really understand your question but I have some idea what you try to say: why use Func class when you can use lambda expressions straight a way?

Easy answer - for example you want to use some lambda expression few times in code so you will need write it multiply times. If you use Func or Action class you just call this class instance and done. Second reason is when you want to pass some lambda expression to the method - it is also done by delegates like Action or Func.

Best Regards
PZ


不,我要问的是表达树优于lambda表达式的优势。



no,what exactly i am asking is advantage of expression tree over lambda expression.

Func<int, int> b = Inc;
Lamda expression
Func<int, int, int> function = (a,b) => a + b;




Console.WriteLine("deleg2(4) = {0}", function (4,5))










Expression<Func<int, int, int>> expression = (a,b) => a + b;
Func<int, int, int> expression = expr.Compile();
Console.WriteLine("deleg2(4) = {0}", expression (4,5));





两者都给出相同的结果。表达式树的优点是什么。



Both are giveing same result.what is the advantage of expression tree.


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

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