C# 如何否定委托?
这是我的代码,为简单起见,大大缩短了C# 如何否定委托?,c#,.net,linq,lambda,delegates,C#,.net,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 =&
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);
Func选择器;
...
选择器=p=>p.IsNew;
...
if(负)//非选择器
选择器=x=>!选择器(x);//这是错误的(导致无限循环)
//你如何否定它?结果应该是p=>!p、 是新的
...
IEnumerable products=MyContext.products.Where(选择器);
您可以使用助手方法执行此操作:
public static Predicate<T> Negate<T>(this Predicate<T> predicate) {
return t => !predicate(t);
}
您的堆栈溢出问题非常明显;您正在根据选择器本身定义选择器。helper方法避免了这个问题
1:也就是说,这显然也会导致堆栈溢出:
public bool M() { return !M(); }
信不信由你,你正在做完全相同的事情。你也可以使用临时函数:
if(negative)
{
Func<Product, bool> tempSelector = selector;
selector = x => !tempSelector(x);
}
if(否定)
{
Func tempSelector=选择器;
选择器=x=>!临时选择器(x);
}
这样,
selector
就不再是指它自己了。看起来你不想要它infinite
那么你想什么时候停止/破坏它?你否定它是什么意思?@KingKing我不明白你的意思@BoltClock在上面的例子中,选择器应该和
p=>一样!p、 IsNew
if(negative)
{
Func<Product, bool> tempSelector = selector;
selector = x => !tempSelector(x);
}