Information Technology Reference
In-Depth Information
var
adder =
Expression
.Lambda<
Func
<T1, T2, TResult>>(
body, leftOperand, rightOperand);
return
adder.Compile()(left, right);
}
This method looks very similar to the previous version; it just enables you
to call it with different types for the left and the right operand. The only
downside is that you need to specify all three parameter types whenever
you call this version:
int
sum2 = AddExpression<
int
,
int
,
int
>(
5
,
7
);
However, because you specify all three parameters, expressions with dis-
similar parameters work:
DateTime
nextWeek= AddExpression<
DateTime
,
TimeSpan
,
DateTime
>(
DateTime
.Now,
TimeSpan
.FromDays(
7
));
It's time to address the other nagging issue. The code, as I have shown so
far, compiles the expression into a delegate every time the AddExpression()
method is called. That's quite inefficient, especially if you end up execut-
ing the same expression repeatedly. Compiling the expression is expen-
sive, so you should cache the compiled delegate for future invocations.
Here's a first pass at that class:
// dangerous but working version
public static class
BinaryOperator
<T1, T2, TResult>
{
static
Func
<T1, T2, TResult> compiledExpression;
public static
TResult Add(T1 left, T2 right)
{
if
(compiledExpression ==
null
)
createFunc();
return
compiledExpression(left, right);
}
private static void
createFunc()
{
var
leftOperand =
Expression
.Parameter(
typeof
(T1),
"left"
);