从表达式中获取结果

9
我已经在运行时创建了一个lambda表达式,并想要评估它 - 我该怎么做呢?我只想单独运行表达式,不针对任何集合或其他值运行。
此时,一旦创建完成,我可以看到它的类型是Expression<Func<bool>>,其值为{() => "MyValue".StartsWith("MyV")}
我认为此时我只需调用var result = Expression.Invoke(expr, null);来运行它,然后就能得到布尔结果。但是这只会返回一个InvocationExpression,在调试器中看起来像{Invoke(() => "MyValue".StartsWith("MyV"))}
我相信我已经接近成功了,但是无法弄清楚如何获得结果!
谢谢。
3个回答

18

尝试使用Compile方法编译表达式,然后调用返回的委托:

using System;
using System.Linq.Expressions;

class Example
{
    static void Main()
    {
        Expression<Func<Boolean>> expression 
                = () => "MyValue".StartsWith("MyV");
        Func<Boolean> func = expression.Compile();
        Boolean result = func();
    }
}

谢谢,这正是我所缺少的。而且解释得很清楚 :) - LJW
只是一点点的语法糖。你可以用一行代码替换最后两行:Boolean result = expression.Compile()(); - Alexandra Rusina

2

正如安德鲁所提到的,您必须在执行表达式之前编译它。另一种选择是完全不使用表达式,看起来像这样:

Func<Boolean> MyLambda = () => "MyValue".StartsWith("MyV");
var Result = MyLambda();

在这个例子中,Lambda表达式在构建项目时被编译,而不是转换为表达式树。如果您没有动态操纵表达式树或使用一个使用表达式树的库(如Linq to Sql,Linq to Entities等),那么按这种方式处理可能更有意义。

在这种情况下,我正在动态创建表达式树,因此需要在运行时编译。谢谢。 - LJW

1
我会采用从这里提取的方法:MSDN示例
delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

如果您想使用 Expression<TDelegate> 类型,则可以参考此页面:System.Linq.Expression 中的 Expression(TDelegate) 类,其中包含以下示例:

// Lambda expression as executable code.
Func<int, bool> deleg = i => i < 5;
// Invoke the delegate and display the output.
Console.WriteLine("deleg(4) = {0}", deleg(4));

// Lambda expression as data in the form of an expression tree.
System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5;
// Compile the expression tree into executable code.
Func<int, bool> deleg2 = expr.Compile();
// Invoke the method and print the output.
Console.WriteLine("deleg2(4) = {0}", deleg2(4));

/*  This code produces the following output:
    deleg(4) = True
    deleg2(4) = True
*/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接