0

我有一个方法接收一个Expression<Func<MyObject, object>>我想通过调用object. 扩展表达式的结果将始终为bool. 本质上我想“转换”Expression<Func<MyObject, object>>Expression<Func<MyObject, bool>>.

这是我想做的事情的要点。我意识到这不会按原样编译ReportExprtype Expression<Func<MyObject, bool>>, not MethodCallExpression,但我认为这传达了意图:

private MyObjectData CreateMyObjectData(string description, 
    FieldTypes fieldType, Expression<Func<MyObject, object>> expression)
{
    var data= new MyObjectData()
    {
        ReportDesc = description,
        FieldType = fieldType,
    };

    var method = typeof(DateTime?).GetMethod("Between");
    Expression<Func<MyObject, DateTime?>> from = x => x.FromValue as DateTime?;
    Expression<Func<MyObject, DateTime?>> to = x => x.ToValue as DateTime?;
    var methodCallExpression = Expression.Call(expression, method, from, to);
    data.ReportExpr = methodCallExpression;
    return data;
}
4

1 回答 1

0

所以你想从(Customer c) => c.SomeDateTime(Customer c) => Between(c.SomeDateTime, a, b)。查看调试器中的示例表达式并了解它们的结构。

该表达式不包含常量。它包含一个参数c。我们可以重用参数:

var cParam = expression.Parameters[0];

接下来我们隔离c.SomeDateTime

var memberAccess = expression.Body;

接下来我们构造新的body:

Expression.Call(
    "Between",
    memberAccess,
    Expression.Constant(DateTime.Now),
    Expression.Constant(DateTime.Now));

接下来是新的 lambda:

var lambda = Expression.Lambda<Func<Customer, bool>>(cParam, body);

即使我忘记了什么,你现在也能弄清楚。

于 2013-08-09T14:42:51.967 回答