2013-07-31 37 views
21

有没有干净的方法来做到这一点?执行LambdaExpression并获取返回值作为对象

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" 

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

+0

为什么不'VAR FUNC =新的Func键(X => {返回的String.Format( “我的INT = {0}”,X);});'? – PoweredByOrange

+1

@PoweredByOrange我假设这个问题被简化了。 – Kevin

+0

@Kevin有意义,否则一个简单的'string.Format()'会这样做:) – PoweredByOrange

回答

29

当然......你只需要编译你的拉姆达,然后调用它...

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

Styxxy带来了一个很好的点...你会得到更好的让编译器为您排忧解难服务。请注意,编译后的表达式与下面的代码中的输入和结果都是强类型的。

var input = 4; 
var compiledExpression = exTyped.Compile(); 
var result = compiledExpression(input); 
+0

'compiledLambda.Invoke(input);'如果确切类型被称为@Styxxy指出的话''可能是更好的选择。 'Invoke'比'DynamicInvoke'更快,因为反射少了,请参阅http://stackoverflow.com/questions/12858340/difference-between-invoke-and-dynamicinvoke – 2016-05-05 21:28:33