如何创建一个使用闭包对象作为参数调用(或与其结合)另一个表达式的表达式?

时间:2013-12-14 12:45:40

标签: c# linq expression-trees

我将首先展示一个不使用表达式树的完全工作的等价物:

public class ClassUsingFuncs
{
    public SomeClass SomeProperty { get; set; }

    public void DoSomethingUsingFuncWithoutArgument(Func<bool> funcWithoutArgument)
    {
    }

    public void DoSomethingUsingFuncWithArgument(Func<SomeClass, bool> funcWithArgument)
    {
        Func<bool> funcWithoutArgument = () => funcWithArgument(SomeProperty);
        DoSomethingUsingFuncWithoutArgument(funcWithoutArgument);
    }
}

使用表达式树时,如何实现此目的?如果我需要LINQKit或其他一些库来实现这一目标,那就没问题了。

public class ClassUsingExpressionTrees
{
    public SomeClass SomeProperty { get; set; }

    public void DoSomethingUsingExpressionWithoutArgument(Expression<Func<bool>> expressionWithoutArgument)
    {
    }

    public void DoSomethingUsingExpressionWithArgument(Expression<Func<SomeClass, bool>> expressionWithArgument)
    {
        Expression<Func<bool>> expressionWithoutArgument = ?
        DoSomethingUsingExpressionWithoutArgument(expressionWithoutArgument);
    }
}

1 个答案:

答案 0 :(得分:1)

public void DoSomethingUsingExpressionWithArgument(Expression<Func<SomeClass, bool>> expressionWithArgument)
{
    var thisExpr = Expression.Constant(this);
    var pExpr = Expression.Property(thisExpr, "SomeProperty");
    var invokeExpr = Expression.Invoke(expressionWithArgument, pExpr);
    Expression<Func<bool>> expressionWithoutArgument = Expression.Lambda<Func<bool>>(invokeExpr);
    DoSomethingUsingExpressionWithoutArgument(expressionWithoutArgument);
}