有什么方法可以分解 Expression<Func<T, Bool>> 并获得相等比较的右侧?

Is there any way of breaking up an Expression<Func<T, Bool>> and get the right hand side of the equality comparison?

这可能不太成功,但我还是会尝试的。

假设我有这些礼仪的表达方式:

public class Foo {
    public int Id { get; set; }
}

Expression<Func<Foo, bool>> expr = p => p.Id == 2;

有什么方法可以分解表达式,比方说:

或者这是不可能的?

Expression<Func<Foo, bool>> expr = p => p.Id == 2; // Supports even p.Id.Equals(2)
BinaryExpression be = expr.Body as BinaryExpression;

if (be != null) 
{
    Expression left = be.Left;
    Expression right = be.Right;
} 
else 
{
    MethodCallExpression mc = expr.Body as MethodCallExpression;

    if (mc != null && mc.Method.Name == "Equals" && mc.Arguments.Count == 1) 
    {
        Expression obj = mc.Object; // "left"
        Expression arg = mc.Arguments[0]; // "right"
    }
    else
    {
        // not supported
    }
}

这里是...

请注意,这仅适用于最简单的情况,其中有一个简单的 BinaryExpressionMethodCallExpression 以及 Equals

但是如果例如表达式是:

Expression<Func<Foo, bool>> expr = p => true;

或...

Expression<Func<Foo, bool>> expr = p => p.Id == 2 && something;

那就不行了