【发布时间】:2022-01-21 22:55:59
【问题描述】:
假设我有一个存储为 Expression
如何组合这些表达式树?
一个更好地解释我想要达到的目标的例子:
Expression<Func<TypeB, bool>> expr1 = (b => b.Where(b.propC.HasFlag(flag))
Expression<Func<TypeB, bool>> expr2 = (b => b.Where(b.propD != null)
...
// Now let's combine these with Or operator
InvocationExpression invocationExpression = Expression.Invoke((Expression) expr2.Expand<Func<typeB, bool>>(), expr1.Parameters.Cast<Expression>());
Expression<Func<typeB, bool>> combinedExpr = Expression.Lambda<Func<typeB, bool>>((Expression) Expression.OrElse(expr1.Body, (Expression) invocationExpression), (IEnumerable<ParameterExpression>) expr1.Parameters);
// To complete my task I need to pass an argument of type Expression<Func<TypeA, bool>> to method, but I am not sure how to build such an expression tree.
// That also could be written as a literal like that:
AddCriterion(objA => objA.propB.Where(b => b.propC.HasFlag(flag) || b.propD != null))
【问题讨论】:
-
这真的没有意义。您如何将谓词“存储为”一种类型但只能“访问”另一种类型?
-
很抱歉造成混淆。我会尽力解释我的意思。