I'm writing the expression extensions method which must inverse the bool
-typed lambda expression.
Here is what I am doing:
public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
return Expression.Lambda<Func<T, bool>>(Expression.Not(e));
}
But this raises an exception, that unary operator is NOT not defined for the type Func<int,bool>
. I also tried this:
public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body));
}
But getting this: Incorrent number of parameters supplied for lambda declaration
.
Fortunately, this is solved this way:
public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body), e.Parameters[0]);
}
Which indicates that .Lambda<>
method needs a parameter, which we need to pass it from source expression.
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.