简体   繁体   English

F#中的通用限制

[英]Generic limitation in F#

Until now, I had a class like this one: 到目前为止,我上过这样的一堂课:

type C<'a when 'a :> A> (...)

But now I created a new type B: 但是现在我创建了一个新的B型:

type B (...) =
    inherit A()

But I don't want C to support B, and this doesn't compile: 但是我不希望C支持B,因此不能编译:

type C<'a when 'a :> A and not 'a :> B> (...)

How can I do that? 我怎样才能做到这一点?

You can't and shouldn't. 你不能也不应。 If B is an A, then C should handle it. 如果B是A,则C应该处理它。 If it's reasonable for C not to be able to handle B, then B shouldn't derive from A. Otherwise you're effectively breaking Liskov's Substitution Principle (or at least a variant of the same). 如果C不能处理B是合理的,则B不应从A派生。否则,您实际上在打破Liskov的“代换原则” (或至少是该原则的一个变体)。

When you declare that B inherits from A, you're saying that it can be used as an A. If that's not the case, you shouldn't be using inheritance. 当您声明B继承自A时,就是说它可以用作A。如果不是这样,则不应使用继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM