Information Technology Reference
In-Depth Information
var rightOperand = Expression .Parameter( typeof (T2),
"right" );
var body = Expression .Add(leftOperand, rightOperand);
var adder = Expression .Lambda< Func <T1, T2, TResult>>(
body, leftOperand, rightOperand);
compiledExpression = adder.Compile();
}
}
At this point, you're probably wondering which technique to use: dynamic
or Expressions. That decision depends on the situation. The Expression
version uses a slightly simpler set of runtime computations. That might
make it faster in many circumstances. However, expressions are a little less
dynamic than dynamic invocation. Remember that with dynamic invoca-
tion, you could add many different types successfully: int and double ,
short and float , whatever. As long as it was legal in C# code, it was legal
in the compiled version. You could even add a string and number. If you
try those same scenarios using the expression version, any of those legal
dynamic versions will throw an InvalidOperationException. Even though
there are conversion operations that work, the Expressions you've built
don't build those conversions into the lambda expression. Dynamic invoca-
tion does more work and therefore supports more different types of oper-
ations. For instance, suppose you want to update the AddExpression to add
different types and perform the proper conversions. Well, you just have to
update the code that builds the expression to include the conversions from
the parameter types to the result type yourself. Here's what it looks like:
// A fix for one problem causes another
public static TResult AddExpressionWithConversion
<T1, T2, TResult>(T1 left, T2 right)
{
var leftOperand = Expression .Parameter( typeof (T1),
"left" );
Expression convertedLeft = leftOperand;
if ( typeof (T1) != typeof (TResult))
{
convertedLeft = Expression .Convert(leftOperand,
typeof (TResult));
}
var rightOperand = Expression .Parameter( typeof (T2),
"right" );
 
Search WWH ::




Custom Search