反转表达式<func <t,bool =“”>&gt; </func <t,>

时间:2012-12-17 09:51:37

标签: c# lambda expression

我正在编写表达式扩展方法,它必须反转bool - 类型的lambda表达式。

这是我正在做的事情:

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

但这引发了一个例外,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));
}

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

1 个答案:

答案 0 :(得分:12)

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

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]);
}

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