代码之家  ›  专栏  ›  技术社区  ›  LJW

从表达式中获取结果

  •  7
  • LJW  · 技术社区  · 15 年前

    我在运行时创建了一个lambda表达式,并希望对其进行计算-我该如何做?我只想单独运行表达式,而不是针对任何集合或其他值。

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

    我当时想我可以打电话 var result = Expression.Invoke(expr, null); 相反,我会得到我的布尔结果。但那只会返回一个 InvocationExpression ,在调试器中 {Invoke(() => "MyValue".StartsWith("MyV"))} .

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

    谢谢。

    3 回复  |  直到 15 年前
        1
  •  14
  •   Andrew Hare    15 年前

    尝试用编译表达式 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();
        }
    }
    
        2
  •  2
  •   Chris Pitman    15 年前

    正如安德鲁提到的,在执行表达式之前必须先编译它。另一种选择是根本不使用表达式,这样做会:

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

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

        3
  •  1
  •   Matt Ellen Bipin Vayalu    15 年前

    我要做的就是从这里开始: MSDN example

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

    如果您想使用 Expression<TDelegate> 然后键入此页: 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
    */