How to create an Expression that invokes (or is combined with) another Expression using a closure object as argument?

StackOverflow https://stackoverflow.com/questions/20583460

  •  01-09-2022
  •  | 
  •  

Frage

I will first show a fully working equivalent that does not use 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);
    }
}

How do I achieve the equivalent for this when using expression-trees? It's no problem if I will need LINQKit or some other library to achieve this.

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);
    }
}
War es hilfreich?

Lösung

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);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top