如何否定委托

本文关键字:何否定 | 更新日期: 2023-09-27 18:26:37

这是我的代码,为简化而缩写

Func<Product, bool> selector;
...
selector = p => p.IsNew;
...
if(negative) // not selector
  selector = x => !selector(x); // This is wrong (causes infinite loop)
  // How do you do negate it? The result should be p => !p.IsNew
...
IEnumerable<Product> products = MyContext.Products.Where(selector);

如何否定委托

您可以使用辅助方法:

public static Predicate<T> Negate<T>(this Predicate<T> predicate) {
    return t => !predicate(t);
}

(或者,将Predicate替换为Func<T, bool>)。

然后:

selector = selector.Negate();

您的堆栈溢出问题非常明显;你用CCD_ 3本身1来定义它。helper方法避免了这个问题。

1:也就是说,这显然也会导致堆栈溢出:

public bool M() { return !M(); }

信不信由你,你在做同样的事情。

您也可以使用临时Func:

if(negative)
{
    Func<Product, bool> tempSelector = selector;
    selector = x => !tempSelector(x);
}

通过这种方式,selector不再指代自身。