反转表达式<Func <T,bool >>

Age*_*ire 5 c# lambda expression

我正在编写表达式扩展方法,它必须反转bool-typed lambda表达式.

这是我在做的事情:

public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
    return Expression.Lambda<Func<T, bool>>(Expression.Not(e));
}
Run Code Online (Sandbox Code Playgroud)

但这引起了例外,那就是unary operator is NOT not defined for the type Func<int,bool>.我也试过这个:

public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
    return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body));
}
Run Code Online (Sandbox Code Playgroud)

但得到这个:Incorrent number of parameters supplied for lambda declaration.

Age*_*ire 13

幸运的是,这是通过这种方式解决的:

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]);
}
Run Code Online (Sandbox Code Playgroud)

这表明该.Lambda<>方法需要一个参数,我们需要从源表达式传递它.