- 浏览: 390053 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (309)
- xaml C# wpf (0)
- scala java inner clas (1)
- Tools UML Eclipse UML2 (1)
- Timer .NET Framework (1)
- perl (6)
- python function paramter (1)
- Python Docstring (1)
- Python how to compare types (1)
- Python (8)
- java (5)
- C# (76)
- C# WPF (0)
- p4 (0)
- WPF (46)
- .net (6)
- xaml (1)
- javascript (40)
- windows (10)
- scala (4)
- winform (1)
- c++ (48)
- tools (12)
- cmd (1)
- os (0)
- CI (0)
- shell (0)
- C (2)
- haskell (49)
- functional (1)
- tool (1)
- gnu (1)
- linux (1)
- kaskell (0)
- svn (0)
- wcf (3)
- android (1)
最新评论
In this post, we are going to discuss the topic on the Expression Tree and Delegate and Lambda, we are going to go through from simple expresison, then expression converted to delegate (lambda), and then we shape up/build up to a more complicated Expression Tree example and we compare it with its equivalent Lambda expression, later we shows why behind Expression Tree since we have the lambda expresion which has hte nice compile time check.
Code as Data
Code as Data is a long existed idea. But it hasn't bee used much in popular programming language. Expression Tree in .NET provides an abstract way of representing the code as a tree of objects. It's like COdeDOM but operate at a slightly higher level. The primary use of Expression tree is in LINQ and you can custom Expression to enable code execution in another end (or even language)
Expression Trees
The namespace in question is "System.Linq.Expression" , of all the classes that is contained in this namespace, Expression is the one that you may use most.
Build a simple expression tree
Let's first see an simple example of Building a exprssion tree
public static void ExploratoryExample() { Expression firstArg = Expression.Constant(2); Expression secondArg = Expression.Constant(3); Expression add = Expression.Add(firstArg, secondArg); Console.WriteLine(add); // this will evaluation the expression tree and does not execute the expression treee, it will print some string representation of the Linq Expression Tree // something like (1 + 2) }
It does almost trivial, it creates two Constant Expression and then made a call Expresion to glue the two together, Graphical representaion is as follow
In the Expression class, there are two properties
Type: the .NET type of the evaluated Expression
NodeType: returns the kind of expression represented , as a member of ExpressoinType enumeration,with values such as LessThan....
As you already know, we have build the ExpressionTree, but we can do barely anything with it, except, Expression has a Compile method which will turnst the Tree representaion of the expresion into executable code piece - a delegate. Below shows how.
public static void ExploratoryExample() { // build expression tree as above // ... Func<int> compiled = Expression.Lambda<Func<int>>(add).Compile(); // Lambda expression can compiled, and once compiled // you can execute it Console.WriteLine("compiled() = {0}", compiled()); }
Now, you will get 5 if you execute the compiled delegate (Func<T> in this case)...
Converting a expression to a expression tree
So this is the other way around of the conversion, and it has a lot of use implicaiton, suppose that you have some code (which is static checked and compiled by the Compiler) and you can convert that readily to expression tree.
A very eimple way of doing that is as follow
// initialize a expression with a delegate // initialization as the conversion Expression<Func<int>> returns5 = () => 5; // you can compile the Expression back to lambda/delegate, as before Func<int> compiled = returns5.Compile(); Console.WriteLine("compiled() = {0}", compiled());
However, the conversion has limitation. In example
- You cannot convert a block of statement (even just one return statement), only single expression is supported
- The expression cannot have assignment
but the list is not exhausted. You will find more at compile time when make such attempt.
To get into details how things works, let see a more complicated expression tree example .Here is the lambda expression code.
Expression<Func<string, string, bool>> expression = (x, y) => x.StartsWith(y); var compiled = expression.Compile(); Console.WriteLine(compiled("First", "Second")); Console.WriteLine(compiled("First", "Fir"));
now let's try to build the expression that matches the code above. This is what we get.
MethodInfo method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) }); var target = Expression.Parameter(typeof(string), "x"); // ((string)x).Method(...) var methodArg = Expression.Parameter(typeof(string), "y"); // x.Method((string) y) Expression[] methodArgs = new[] { methodArg }; // methods args -- composite -->* methodArg Expression call = Expression.Call(target, method, methodArgs); // x.StartsWith(y) var lambdaParamters = new[] { target, methodArg }; // (x, y) -- (target, methodArgs) -- (arg1, arg2) => ... // it is difficult to figure out the argument types //var lambda = Expression.Lambda(call, methodArgs); // so you would probably indicate what is the type of the Lambda expression var lambda = Expression.Lambda<Func<string, string, bool>> (call, lambdaParamters); var compiled = lambda.Compile(); Console.WriteLine("First", "Second"); Console.WriteLine("First", "Fir");
A bit chunky, let's see the Expresion tree in its Graphic representation. See below.
HINT, you can visualize the Expression Tree from the Text Visualizer.
Expression Tree at the heart of LINQ.
Without lambda expresison, Expression Tree would have little value. They'd be an alternative to CodeDOM.
It is also ture for the reverse to a limited extent: without expression trees, lambda expression would certainmly be less useful. HAVing a more compact way of creating delegate would be welcome, and hte shift towards a more functinal development model would still be viable. Lambda expression are particular effective when combined with extension methods. But with expresion tree in the picture as well, things get a lot more interesting.
Lambda expression provide:
Compile-check
Expression Tree provides:
abstract the execution model away from the desired logic.
LINQ to SQL is good example of combination of Lamdba Expression and Expression Tree.
发表评论
-
wpf - example to enhance ComboBox for AutoComplete
2014-09-19 15:56 1942first let’s see an example ... -
Investigate and troubleshoot possible memory leak issue of .NET application
2014-07-31 10:42 0Hi All, I would like to sh ... -
C# – CoerceValueCallback合并、替换元数据值
2013-08-05 21:59 1895Topic: C# – CoerceValueCallbac ... -
wpf – ListView交替背景色
2013-07-02 20:56 6496Wpf – Alternate background col ... -
C# - 简单介绍TaskScheduler
2013-06-29 17:18 11946标题: C# - 简单介绍TaskSchedulerTit ... -
c# - Get enum from enum attribute
2013-06-27 21:32 1202DescriptionAttribute gives the ... -
C# - PInvoke, gotchas on the RegisterClassEx and the CreateWindowEx
2013-06-24 13:49 2537I get an exception message li ... -
c# - Use PInvoke to create simple win32 Application
2013-06-24 11:59 10890In this post, .net platform h ... -
c# - Linq's Select method as the Map function
2013-06-19 18:47 1248If you comes from a functiona ... -
c# - Tips of Linq expression Any to determine if a collection is Empty
2013-06-19 18:29 896When you are @ the linq expres ... -
myth buster - typeof accepting array of types not acceptable
2013-06-19 17:17 783I have seen from some book whe ... -
windows - trying to create WIN32 application with PInvoke
2013-06-19 14:34 0While it is stupid to do such ... -
WPF - Setting foreground color of Entire window
2013-06-13 16:00 1882You might as well as I would s ... -
WPF - Enhanced TabControl - TabControlEx aka Prerendering TabControl
2013-06-13 13:12 5294As an opening word, let's che ... -
wpf - ControlTemplate and AddLogicChild/RemoveLogicalChild
2013-06-10 15:42 1149Recently I was trying to debug ... -
c# - P/Invoke, DllImport, Marshal Structures and Type conversions
2013-06-05 15:25 1663P/Invoke as in the following q ... -
c# - A study on the NativeWindow - encapsulate window handle and procedure
2013-06-05 14:40 6046NativeWindow gives you a way t ... -
WCF - Notify server when client connects
2013-06-03 18:19 1183It is sometimes very importan ... -
wcf - Debug to enable Server exception in Fault message
2013-06-03 15:47 1059WCF will be able to send back ... -
c# - determine if a type/object is serialzable
2013-05-30 16:35 840In WCF, primitives type are s ...
相关推荐
Apress - Java Closures and Lambda.2015
sqs-to-lambda-via-lambda, 向Lambda函数交付SQS队列项( 使用 Lambda ) 到 Lambda ( 通过 Lambda )当前没有用于Lambda的本机SQS事件源。 这种情况很糟糕。你可以运行类似于但是需要运行一个实例,谁想这样做。?运行...
aws-lambda-go-event, AWS Lambda事件源的类型定义 eawsy/aws-lambda-go-eventAWS Lambda事件源的类型定义和帮助器。 使用 ,让你无需提供或者管理服务器即可运行代码。 使用 eawsy/aws-lambda-go-shi
dynamodb-lambda-autoscale, 使用Lambda实现自动缩放 DynamoDB dynamodb-lambda-autoscale使用 AWS Lambda函数 自动缩放 AWS DynamoDB5 分钟设置过程无服务器设计通过配置样式实现灵活的代码自动缩放表和全局二级...
开源项目-mtojek-aws-lambda-go-proxy.zip,mtojek/aws-lambda-go-proxy: Pass Lambda events to the application running on your machine | Debug real traffic locally | Forget about redeployments
Ansible-chrome-aws-lambda.zip,用于aws lambda和google云功能的chrome aws lambda二进制文件,ansible是一个简单而强大的自动化引擎。它用于帮助配置管理、应用程序部署和任务自动化。
python好找工作吗-23-了解lambda.ev4.rar
python好找工作吗-24-体验lambda.ev4.rar
资源分类:Python库 所属语言:Python 资源全名:mypy-boto3-lambda-1.17.104.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
python库。 资源全名:mypy-boto3-lambda-1.17.58.0.tar.gz
python库。 资源全名:mypy-boto3-lambda-1.17.72.tar.gz
资源来自pypi官网。 资源全名:mypy-boto3-lambda-1.12.12.0.tar.gz
资源来自pypi官网。 资源全名:mypy-boto3-lambda-1.17.88.post1.tar.gz
资源来自pypi官网。 资源全名:mypy-boto3-lambda-1.18.13.tar.gz
资源来自pypi官网。 资源全名:mypy-boto3-lambda-1.17.78.tar.gz
资源来自pypi官网。 资源全名:mypy-boto3-lambda-1.17.48.0.tar.gz
资源来自pypi官网。 资源全名:mypy-boto3-lambda-1.10.39.2.tar.gz
10.C# 知识回顾 - Lambda.pdf10.C# 知识回顾 - Lambda.pdf
c++初学教程-第2课-命令行计算器_lambda_vector