Liskov Substition and Composition

风流意气都作罢 提交于 2019-11-28 20:52:30

I'm afraid the short answer is, you can't without doing what is required, i.e. pass the composed instance variable instead.

You could allow an implicit or explicit cast to that type (whose implementation simply passed the composed instance) but this would, IMO be pretty evil.

sixlettervariable's answer is good and I won't rehash it but if you indicated which classes you wished you could extend we might be able to tell you why they prevented it.

I found myself asking that same question until I started working on reusable libraries of my own. Many times you wind up with certain classes that just cannot be extended without requiring obscure or arcane sequences of calls from the implementor.

When allowing your class to be extended, you have to ask: if a developer extends my class, and passes this new class to my library, can I transparently work with this new class? Can I work properly with this new class? Is this new class really going to behave the same?

I've found that most of the time the sealed classes in the .Net Framework have certain under-the-hood requirements that you aren't aware of, and that given the current implementation cannot be safely exposed to subclasses.

This doesn't exactly answer your question, but it provides insight as to why not all classes are inheritable in the .Net Framework (and why you should probably entertain sealing some of your classes too).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!