繁体   English   中英

反转表达式<Func<T, bool> &gt;

[英]Invert the Expression<Func<T, bool>>

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM