我将首先展示一个不使用表达式树的完全工作的等价物:
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);
}
}
答案 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);
}