如何否定代表?

Axi*_*ili 4 .net c# linq lambda delegates

这是我的代码,为简单起见,大量缩写

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);
Run Code Online (Sandbox Code Playgroud)

jas*_*son 7

您可以使用辅助方法执行此操作:

public static Predicate<T> Negate<T>(this Predicate<T> predicate) {
    return t => !predicate(t);
}
Run Code Online (Sandbox Code Playgroud)

(或,替换PredicateFunc<T, bool>).

然后:

selector = selector.Negate();
Run Code Online (Sandbox Code Playgroud)

堆栈溢出问题非常明显; 你是selector用自己来定义的1.辅助方法避免了这个问题.

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

public bool M() { return !M(); }
Run Code Online (Sandbox Code Playgroud)

信不信由你,你做的完全一样.