Information Technology Reference
In-Depth Information
body, leftOperand, rightOperand);
Func <T, T, T> theDelegate = adder.Compile();
return theDelegate(left, right);
}
Most of the interesting work involves type information, so rather than
using var as I would in production code for clarity, I've specifically named
all the types.
The first two lines create parameter expressions for variables named “left”
and “right,” both of type T. The next line creates an Add expression using
those two parameters. The Add expression is derived from BinaryExpres-
sion. You should be able to create similar expressions for other binary
operators.
Next, you need to build a lambda expression from the expression body
and the two parameters. Finally, you create the Func<T,T,T> delegate by
compiling the expression. Once compiled, you can execute it and return
the result. Of course, you can call it just like any other generic method:
int sum = AddExpression( 5 , 7 );
I added the comment above the last example indicating that this was a
naïve implementation. DO NOT copy this code into your working appli-
cation. This version has two problems. First, there are a lot of situations
where it doesn't work but Add() should work. There are several examples
of valid Add() methods that take dissimilar parameters: int and double ,
DateTime and TimeSpan, etc. Those won't work with this method. Let's
fix that. You must add two more generic parameters to the method. Then,
you can specify different operands on the left and the right side of the
operation. While at it, I replaced some of the local variable names with
var declarations. This obscures the type information, but it does help
make the logic of the method a little more clear.
// A little better.
public static TResult AddExpression<T1, T2, TResult>
(T1 left, T2 right)
{
var leftOperand = Expression .Parameter( typeof (T1),
"left" );
var rightOperand = Expression .Parameter( typeof (T2),
"right" );
var body = Expression .Add(leftOperand, rightOperand);
 
Search WWH ::




Custom Search