我在运行时创建了一个 lambda 表达式,并且想要对其求值 - 我该怎么做?我只想单独运行表达式,而不是针对任何集合或其他值。
在此阶段,一旦创建,我可以看到它的类型为 Expression>
,值为 {() =>; “MyValue”.StartsWith(“MyV”)}
。
我当时想我可以调用 var result = Expression.Invoke(expr, null);
来反对它,并且我会得到布尔结果。但这只是返回一个 InvocableExpression
,它在调试器中看起来像 {Invoke(() => "MyValue".StartsWith("MyV"))}
。
我很确定我已经接近了,但不知道如何获得结果!
谢谢。
I've created a lambda expression at runtime, and want to evaluate it - how do I do that? I just want to run the expression by itself, not against any collection or other values.
At this stage, once it's created, I can see that it is of type Expression<Func<bool>>
, with a value of {() => "MyValue".StartsWith("MyV")}
.
I thought at that point I could just call var result = Expression.Invoke(expr, null);
against it, and I'd have my boolean result. But that just returns an InvocationExpression
, which in the debugger looks like {Invoke(() => "MyValue".StartsWith("MyV"))}
.
I'm pretty sure I'm close, but can't figure out how to get my result!
Thanks.
发布评论
评论(3)
尝试使用
Compile
方法编译表达式然后调用返回的委托:Try compiling the expression with the
Compile
method then invoking the delegate that is returned:正如安德鲁提到的,您必须先编译表达式才能执行它。另一种选择是根本不使用表达式,它看起来像这样:
在本例中,lambda 表达式是在构建项目时编译的,而不是转换为表达式树。如果您不动态操作表达式树或使用使用表达式树的库(Linq to Sql、Linq to Entities 等),那么这样做更有意义。
As Andrew mentioned, you have to compile an Expression before you can execute it. The other option is to not use an Expression at all, which woul dlook like this:
In this example, the lambda expression is compiled when you build your project, instead of being transformed into an expression tree. If you are not dynamically manipulating expression trees or using a library that uses expression trees (Linq to Sql, Linq to Entities, etc), then it can make more sense to do it this way.
我的做法是从这里开始的: MSDN 示例
另外,如果您想使用
Expression
类型,则此页面:Expression(TDelegate) 类 (System.Linq.Expression) 有以下示例:The way I would do it is lifted right from here: MSDN example
Also if you want to use an
Expression<TDelegate>
type then this page: Expression(TDelegate) Class (System.Linq.Expression) has the following example: