views:

76

answers:

2

I've tried to understand some of the posts of similar, but don't quite understand their purposes and thought I'd explain my own...

I have a class -- fully defined with code with properties, and methods. Many methods are virtual to be overriden by further derived class. So, I have something like the following

Class_Main
  --  Class_A : Class_Main
  --  Class_B : Class_Main
  --  Class_C : Class_Main
  --  Class_D : Class_Main

I then need to define one more class that can be dynamically derived from A-D... such as:

Class_X : Class_A (or Class_B or Class_C or Class_D )

as I have additional properties and methods within the Class_X. Since C# can't derive from two actual classes, but can use interfaces, but you can't have code in an interface, just abstract signatures, how might I go about doing such implementation.

Thanks

A: 

Extend from one class and include the other class within Class X, and just have adapter methods to map directly to the class inside.

So, now exactly C#, just prototyping:

class ClassA {
  public void FunctionClassA(...) { ... }
  public void FunctionClassB(...) { ... }
}

class ClassX : ClassB {
  private ClassA classa;
  public ClassX() {
     classa = new ClassA();
  }
  public void FunctionClassA(...) { classa.FunctionClassA(...); }
}

So, ClassX now has one function inherited (by appearance) from ClassA, and contains all the methods of ClassB.

James Black
+1  A: 

What you are describing sounds a bit like duck typing. This isn't available in C#, as it is a statically-typed language. Perhaps when C# 4 comes around, dynamic will give you what you are looking for.

If Class_X needs to be "filled in" with functionality from those classes, it would be common to pass that into the class at the time of instantiation:

public class Class_X {
    private Class_Main _impl;
    public Class_X(Class_Main impl) {
        _impl = impl;
    }
}

Class_X classXA = new Class_X(new Class_A());
Class_X classXB = new Class_X(new Class_B());

At this point, your Class_X instances have access to the Class_Main properties & methods for all derived classes. This doesn't make Class_X an aggregate, just enables you to use the runtime behavior of any Class_Main from within Class_X (through the _impl object).

jheddings
This was kind-of what I was thinking, but didn't know if there was another way... then my methods of class_X would do something likereturn _impl.SomeFunction(whateverParam) .. thanks
DRapp