3

Expression动态创建树时如何创建演员表?

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

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

而且我想一般地创建一个强类型的 lambda 表达式,表示一个返回object而不是string( Expression<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)?

4

1 回答 1

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;
}
于 2012-08-02T14:28:24.067 回答