附加表达式创建不同类型的表达式

时间:2013-08-09 14:18:01

标签: c# expression

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

以下是我想做的事情的要点。我意识到这不会编译,因为ReportExpr类型为Expression<Func<MyObject, bool>>,而不是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;
}

1 个答案:

答案 0 :(得分:0)

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

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

var cParam = expression.Parameters[0];

接下来我们隔离c.SomeDateTime;

var memberAccess = expression.Body;

接下来我们构建新的主体:

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

接下来是新的lambda:

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

即使我忘记了某些东西,你现在也能解决它。