【问题标题】:Invert the Expression<Func<T, bool>>反转表达式<Func<T, bool>>
【发布时间】:2012-12-17 09:51:36
【问题描述】:

我正在编写表达式扩展方法,该方法必须反转 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&lt;int,bool&gt;。 我也试过这个:

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

【问题讨论】:

    标签: c# lambda expression


    【解决方案1】:

    幸运的是,这是这样解决的:

    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&lt;&gt;方法需要一个参数,我们需要从源表达式中传递它。

    【讨论】:

    • 如果没有任何参数,你应该可以通过null我想?就像你做Method.Invoke 一样,只是好奇是不是这样。
    • e.Parameters[0] 将抛出异常,如果没有定义参数。
    • @HamletHakobyan 无法指定无参数,因为此扩展的泛型类型是Func&lt;T, bool&gt;,其中T 是参数。传递 null 将导致提取该 null,而不是引发 IndexOutOfBounds 或任何其他异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多