Convert Expression to Expression.Lambda<Func<object, b
本文关键字:lt Expression object Func Convert Lambda to | 更新日期: 2023-09-27 18:33:11
>我有一个方法,它根据传递给该方法的对象的类型构建表达式树。构建树后,我想转换它并使用返回类型返回它,如下所示。
public static Expression<Func<object, bool>> BuildExpression(Type type, ...)
{
// build the expression...
ParameterExpression param = Expression.Parameter(type, "m");
Expression expression = null;
// simplified version of building the expression tree
MemberExpression member = Expression.Property(param, filter.Property);
ConstantExpression constant = Expression.Constant(filter.Value);
expression = Expression.Equal(member, constant);
// ...
// IT FAILS ON THIS LINE!!!
return Expression.Lambda<Func<object, bool>>(expression, param);
}
我看了一些转换答案,但无济于事。有什么建议吗?
这是我之前评论中所述的经过修改的代码。
1) 您的函数返回描述具有单个参数的函数的表达式。这个论点属于Object
型.因此,在创建参数"m"表达式时应使用Object
类型。
2)在访问属性参数之前,应强制转换回所需的类型。请参阅Expression.Convert
。
public static Expression<Func<object, bool>> BuildExpression(Type type, ...)
{
// build the expression...
ParameterExpression param = Expression.Parameter(typeof(Object), "m");
Expression expression = null;
UnaryExpression convert = Expression.Convert(param, type);
// simplified version of building the expression tree
MemberExpression member = Expression.Property(convert, filter.Property);
ConstantExpression constant = Expression.Constant(filter.Value);
expression = Expression.Equal(member, constant);
// ...
return Expression.Lambda<Func<object, bool>>(expression, param);
}