【问题标题】:Getting the result from an Expression从表达式中获取结果
【发布时间】:2009-12-06 18:53:17
【问题描述】:

我在运行时创建了一个 lambda 表达式,并且想要对其进行评估 - 我该怎么做?我只想自己运行表达式,而不是针对任何集合或其他值。

在这个阶段,一旦它被创建,我可以看到它的类型是Expression<Func<bool>>,值为{() => "MyValue".StartsWith("MyV")}

当时我想我可以直接调用var result = Expression.Invoke(expr, null); 反对它,我会得到我的布尔结果。但这只是返回一个InvocationExpression,在调试器中看起来像{Invoke(() => "MyValue".StartsWith("MyV"))}

我很确定我已经接近了,但不知道如何得到我的结果!

谢谢。

【问题讨论】:

    标签: c# lambda expression-trees


    【解决方案1】:

    尝试使用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();
        }
    }
    

    【讨论】:

    • 谢谢,正是我所缺少的。并且解释清楚:)
    • 只是一点语法糖。您可以只用一行替换最后两行: Boolean result = expression.Compile()();
    【解决方案2】:

    正如 Andrew 所说,您必须先编译一个表达式,然后才能执行它。另一种选择是根本不使用表达式,看起来像这样:

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

    在此示例中,lambda 表达式在您构建项目时进行编译,而不是转换为表达式树。如果您不是动态操作表达式树或使用使用表达式树的库(Linq to Sql、Linq to Entities 等),那么这样做会更有意义。

    【讨论】:

    • 在这种情况下,我正在动态创建表达式树,因此需要在运行时进行编译。不过还是谢谢。
    【解决方案3】:

    我的做法是从这里提出来的:MSDN example

    delegate int del(int i);
    static void Main(string[] args)
    {
        del myDelegate = x => x * x;
        int j = myDelegate(5); //j = 25
    }
    

    此外,如果您想使用 Expression&lt;TDelegate&gt; 类型,则此页面:Expression(TDelegate) Class (System.Linq.Expression) 具有以下示例:

    // 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
    */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多