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

8

我正在编写表达式扩展方法,必须反转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));
}

但这引发了一个异常,即类型为 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));
}

但是你可能会得到这个错误:为lambda声明提供了不正确的参数数量
1个回答

21
幸运的是,这个问题可以这样解决:
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<>方法需要一个参数,我们需要从源表达式传递它。

如果没有任何参数,你应该可以传递 null 吧?就像当你执行 Method.Invoke 时一样,我只是好奇这是否成立。 - LukeHennerley
如果没有定义参数,e.Parameters[0]会抛出异常。 - Hamlet Hakobyan
1
@HamletHakobyan,无法指定无参数,因为此扩展的通用类型为Func<T, bool>,其中T是参数。传递null将导致提取该null,而不是引发IndexOutOfBounds或任何其他异常。 - AgentFire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接