Is there a way to derive from a class with an internal constructor?

后端 未结 6 430
遥遥无期
遥遥无期 2020-12-20 13:19

I\'m working with a 3rd party c# class that has lots of great methods and properties - but as time has gone by I need to extend that class with methods and properties of my

6条回答
  •  一向
    一向 (楼主)
    2020-12-20 13:44

    You ask: "Why limit the ability to subclass?"

    Because designing for inheritance is tricky, particularly if you're designing for other developers to inherit from your class. As Josh Bloch says in Effective Java, you should design for inheritance or prohibit it. In my view, unless you have a good reason to design for inheritance, you shouldn't do so speculatively.

    Does the class implement an interface which you could also implement (possibly by proxying most calls back to an instance of the original)? There's often no really elegant answer here - and the best solution will depend on the exact situation, including what you're trying to add to the class.

    If you're not adding any more state - just convenience methods, effectively - then extension methods may work well for you. But they don't change what data an object is capable of storing, so if you need to add your own specialised data, that won't work.

提交回复
热议问题