How to reuse code if multiple inheritance is not an option?

I would like to use several methods from several of my old tested classes in my new class that I am creating. Unfortunately, C # does not support multiple inheritance. How to reuse code from these old classes? Am I just creating them as member objects? or do i have other options?

+1
source share
6 answers

Generally, using composition instead of inheritance is the way forward, yes. If you could give a concrete example of what you mean, this would facilitate the search for a suitable approach: it is not always the same.

+11
source

Using them as member objects should be a good idea. Then you can also set only the methods of interest to them and adapt them if necessary.

+4
source

, .

public static void MyMethod( this MyType target ){}


MyType.MyMethod()

, , MyType , , , .

public class MyDerived : MyType{}

MyDerived.MyMethod()
+4

, # , .

, .

, , , , "-". , .

, :

http://www.freeimagehosting.net/uploads/cb219cefba.jpg

, IBreeper Breeper .

, . :

  • . ;

  • " " . , SuperFuddler ( , ), God Object, ;

  • , , SuperFuddler. .

+2
source

You can easily fake it as follows:

public interface IFoo {
    void DoFoo();
}

public class Foo : IFoo {
    public void DoFoo() { Console.Write("Foo"); }
}

public class Bar {
    public void DoBar() { Console.Write("Bar"); }
}

public class FooBar : IFoo, Bar {
    private IFoo baseFoo = new Foo();
    public void DoFoo() { baseFoo.DoFoo(); }
}

//...

FooBar fooBar = new FooBar();

fooBar.DoFoo();
fooBar.DoBar();
0
source

if you developed them as a component, use them do not inherit from them

-1
source

All Articles