简体   繁体   中英

Creating which derived type of class at runtime

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 AD... 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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM