I would like to make use of few methods from couple of my old tested classes into my new class that I am building. Unfortunately, C# does not support multiple inheritance. How do I reuse code from these old classes? Do I just create them as member objects? or Do I have any other options?
相关问题
- how to define constructor for Python's new Nam
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- Keeping track of variable instances
Using them as member objects should be a good idea. Then you can also expose only the methods of interest, and adapt them if necessary.
You can fake it pretty easily like this:
Generally, using composition instead of inheritance is the way forward, yes. If you could give a concrete example of the kind of thing you mean, that would make it easier to help find the appropriate approach though: it's not always the same.
You can recreate then as extension methods when they work on the same type.
as noted below, if you have a class which derives from MyType or more common implements the interface the extension method works on, the extension works for those.
Technically, C# implements multiple interface inheritence, but not multiple implementation inheritence.
The problem with multiple implementation inheritence is that it leads to situations like the diamond problem.
You can simulate multiple implementation inheritence using multiple interface inheritence and composition, which is close to what you described as creating the objects that you want to re-use "as member objects". What you don't want to do, however is expose unnecessary behaviour from your wrapped type.
Following is a class diagram showing the basic principle of multiple inheritence through composition:
Multiple Inheritance http://www.freeimagehosting.net/uploads/cb219cefba.jpg
The drawback of this is that any changes to the interface IBreeper will require corresponding changes to Breeper, and vice versa.
Taking a step back though - you need to carefully look at the reasons for composing the old classes. Is it to:
Enhance or step up existing behaviour. You should then consider the Proxy Pattern;
Create a "one stop shop" for all of your behaviour. You should really only be doing this if your SuperFuddler is cohesive (that is, all exposed behaviour is aligned), otherwise you'll be moving into a God Object situation which isn't conducive to being maintainable;
Present an interface that is more consistent with a mode of use required by a certain class of clients of your SuperFuddler. In this case, you should consider the Adapter Pattern.
if you have developed them as a component , use them dont inherite from them