[英]Convert Expression to Expression.Lambda<Func<object, bool>>
I have a method that builds an expression tree, based on the Type of the object that is passed to the method. 我有一个根据传递给该方法的对象的类型来构建表达式树的方法。 Once the tree is built, I want to convert it and return it with the return type as is shown below. 生成树后,我要对其进行转换,并使用如下所示的返回类型将其返回。
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);
}
I've looked at a few conversion answers, but to no avail. 我看了一些转换答案,但无济于事。 Any advice? 有什么建议吗?
Here is your code with modifications as described in my previous comment. 这是经过修改的代码,如我之前的评论中所述。
1) Your function returns expression that describes function with single argument. 1)您的函数返回使用单个参数描述函数的表达式。 And this argument is of type Object
. 这个参数是Object
类型的。 So you should use Object
type when creating parameter "m" expression. 因此,在创建参数“ m”表达式时应使用Object
类型。
2) Before accessing the property parameter should be cast back to desired type. 2)在访问属性参数之前,应将其强制转换回所需的类型。 See Expression.Convert
. 参见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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.