簡體   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