To make a lambda expression be treated as an expression tree, assign or cast it to the type Expression<T>, where T is the type of the delegate that defines the expression's signature.
Lambda expressions can be used as expression trees (hierarchies of objects defining the components of an expression – operators, property access sub-expressions, etc) instead of being directly turned to code. This way, the expressions can be analyzed at runtime.
When a lambda expression is assigned to a variable of type Expression
Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.
This expression tree can also be created manually like this:
Collapse | Copy Code
Expression<Predicate<int>> expression = Expression.Lambda<Predicate<int>>(
Expression.LT(
Expression.Parameter(typeof(int), "n"),
Expression.Constant(10)
),
Expression.Parameter(typeof(int), "n")
);
An expression tree can be compiled and turned into a delegate using the Compile() method of the Expression<T>class:
//Get a compiled version of the expression, wrapped in a delegate
Predicate<int> predicate=expression.Compile();
//use the compiled expression
bool isMatch=predicate(8); //isMatch will be set to true
The Compile() method dynamically compiles IL code based on the expression, wraps it in a delegate so that it can be called just like any other delegate, and then returns the delegate
Code Sample
The following code example demonstrates how to create an expression tree that represents the lambda expression num => num < 5 (C#) or Function(num) num < 5 (Visual Basic) by using the API.
// Add the following using directive to your code file:
// using System.Linq.Expressions;
// Manually build the expression tree for
// the lambda expression num => num < 5.
ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
Expression<Func<int, bool>> lambda1 =
Expression.Lambda<Func<int, bool>>(
numLessThanFive,
new ParameterExpression[] { numParam });
No comments:
Post a Comment