我想从 Predicate 派生一个类,但看起来好像 Predicate<> 被密封。 就我而言,我只想返回指定函数的反转(!)结果。 我还有其他方法来实现目标。 我的问题是,MS 设计者在决定密封 Predicate<> 时可能会想到什么?
没有太多思考,我想出了:
(a) 简化了他们的测试,只是时间与成本的权衡
(b)“没有好处”可能来自于Predicate<>的派生;
你怎么认为?
更新:有 n 个谓词在初始化阶段动态添加到谓词列表中。 每个都是互斥的(如果添加了 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
并不是我无法解决问题,而是我想知道为什么我不能以某种方式解决它。
I wanted to derive a class from Predicate<IMyInterface>, but it appears as if Predicate<> is sealed. In my case I wanted to simply return the inverted (!) result of the designated function. I have other ways to accomplish the goal. My question is what might the MS designers have been thinking when deciding to seal Predicate<>?
Without much thought I came up with:
(a) simplified their testing, just a time vs cost trade off
(b) "no good" could come from deriving from Predicate<>
What do you think?
Update: There are n predicates that are dynamically added to a list of Predicates during an initialization phase. Each is mutually exclusive (if Abc is added, NotAbc wont be added). I observed a pattern that looks like:
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
Its not that I can't solve the problem, its that I wonder why I couldn't solve it a certain way.
发布评论
评论(3)
Predicate
是委托类型。 你永远无法从代表那里获得利益。老实说,无论如何,继承在这里似乎并不真正合适 - 只需编写一个返回原始方法的逆方法即可。 就这么简单:
Predicate<T>
is a delegate type. You can never derive from delegates.To be honest, it doesn't sound like inheritance is really appropriate here anyway - just write a method which returns an inverse of the original. It's as simple as this:
谓词是委托。 您不能从委托类型继承。
如果您想获得反转值,请使用以下命令:
Predicate is a delegate. You can not inherit from a delegate type.
If you want to get the inverted value, use the following:
委托的功能是处理类型安全方法指针的列表。 C# 设计者已决定无需向此功能添加任何内容,也没有理由更改委托的行为。
所以,乔恩是对的,继承在这里不合适。
代表可以指向方法列表。 我们使用 += 运算符或 Delegate.Combine 添加到此列表中。 如果方法的签名不为空,则返回最后调用的方法的结果(如果调用正确)。
The functionality of a delegate is to handle a list of type safe method pointers. C# designers have decided that there is nothing to add to this functionality and there is no reason to change the behavior to delegates.
So, Jon is right, inheritance is not appropriate here.
Delegates can point to a list of methods. We add to this list with += operator or with Delegate.Combine. If the signature of the method is not void then the result of the last invoked method is returned (if a recall correctly).