如何在动态创建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
)?
答案 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;
}