为什么Predicate <>密封?

Gre*_*lac 5 c# predicate

我想从Predicate <IMyInterface>派生一个类,但看起来好像Predicate <>是密封的.在我的情况下,我想简单地返回指定函数的反转(!)结果.我有其他方法来实现这个目标.我的问题是,在决定密封Predicate <>时,MS设计师一直在考虑什么?

我没有想太多想法:(a)简化了他们的测试,只是时间与成本之间的关系(b)"没有好处"可能来自Predicate <>

你怎么看?

更新:在初始化阶段,有n个谓词动态添加到Predicates列表中.每个都是互斥的(如果添加了Abc,则不会添加NotAbc).我观察到一种模式,看起来像:

bool Happy(IMyInterface I) {...}
bool NotHappy(IMyInterface I) { return !Happy(I); }
bool Hungry(IMyInterface I) {...}
bool NotHungry(IMyInterface I) { return !Hungry(I); }
bool Busy(IMyInterface I) {...}
bool NotBusy(IMyInterface I) { return !Busy(I); }
bool Smart(IMyInterface I) {...}
bool NotSmart(IMyInterface I) {...} //Not simply !Smart
Run Code Online (Sandbox Code Playgroud)

它不是我无法解决问题,它我想知道为什么我无法以某种方式解决它.

Jon*_*eet 20

Predicate<T>是委托类型.你永远不能从代表派生出来.

说实话,这听起来并不像继承在这里真正适合 - 只需编写一个返回原始逆的方法.这很简单:

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


Ome*_*ten 4

谓词是委托。您不能从委托类型继承。如果您想获得反转值,请使用以下命令:

Predicate<T> p;
Predicate<T> inverted = t => !p(t);
Run Code Online (Sandbox Code Playgroud)