34

有没有一种干净的方法可以做到这一点?

Expression<Func<int, string>> exTyped = i => "My int = " + i;
LambdaExpression lambda = exTyped;

//later on:

object input = 4;
object result = ExecuteLambdaSomeHow(lambda, input);
//result should be "My int = 4"

这应该适用于不同的类型。

4

1 回答 1

41

Sure... you just need to compile your lambda and then invoke it...

object input = 4;
var compiledLambda = lambda.Compile();
var result = compiledLambda.DynamicInvoke(input);

Styxxy brings up an excellent point... You would be better served by letting the compiler help you out. Note with a compiled expression as in the code below input and result are both strongly typed.

var input = 4;
var compiledExpression = exTyped.Compile();
var result = compiledExpression(input);
于 2013-07-31T22:01:13.987 回答