简体   繁体   中英

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. And this argument is of type Object . So you should use Object type when creating parameter "m" expression.

2) Before accessing the property parameter should be cast back to desired type. See 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM