转换Expression.Property结果

时间:2012-08-02 14:24:56

标签: c# reflection expression-trees

如何在动态创建Expression树时创建强制转换?

问题是,我有string类型的属性:

public class Test
{
    public string Id { get; set; }
}

我想一般创建一个强类型的lambda表达式,表示一个返回object而不是stringExpression<Func<T, object>>)的委托。

现在我正在这样做:

private static Expression<Func<T, object>> CreateIdQuery()
{
    Type type = typeof(T);
    PropertyInfo idProperty = type.GetProperty("Id");
    ParameterExpression lambdaParam = Expression.Parameter(type, "x");
    MemberExpression body = Expression.Property(lambdaParam, idProperty);
    LambdaExpression expr = Expression.Lambda(body, lambdaParam);
    return (Expression<Func<T, object>>)expr;
}

但它在最后一行引发异常(我无法将Expression<Func<Test, string>>强制转换为Expression<Func<Test, object>>)。

我如何转换表达式的主体(我假设MemberExpression部分需要转换为object)?

1 个答案:

答案 0 :(得分:7)

使用Expression.Convert(body, typeof(object))

private static Expression<Func<T, object>> CreateIdQuery()
{
    Type type = typeof(T);
    PropertyInfo idProperty = type.GetProperty("Id");
    ParameterExpression lambdaParam = Expression.Parameter(type, "x");
    MemberExpression body = Expression.Property(lambdaParam, idProperty);
    UnaryExpression converted = Expression.Convert(body, typeof(object));
    LambdaExpression expr = Expression.Lambda(converted, lambdaParam);
    return (Expression<Func<T, object>>)expr;
}