lundi 8 avril 2019

Pattern to avoid the need for Downcasting/Reflection

Suppose I have two implementations of a base class:

public class Base { 
    public string Stringify() { return "I am a member of base class"; }
}

public class A : Base {
    public void DoAThing() {...};
}

public class B : Base {
    public void DoBThing(int anInteger) {...};
}

Suppose I want to put many instances of Base in a list, so that I can loop over them and call Stringify() on each, and make use of their shared functionality.

static void Main(string[] args)
{
    A thing1 = new A();
    B thing2 = new B();
    B thing3 = new B();     
    List<Base> list = new List<Base> {thing1, thing2, thing3};
    foreach(Base base in list) { Console.WriteLine(base.Stringify()); }           
}

Now suppose there are many many Base objects, such that maintaining the individual thing references to each one is not realistic. Would there be any way, via only the list, to regain the DoAThing() or DoBThing() functionality that is lost by the abstraction without having to use explicit downcasting and reflection?

This feels like it would be a common enough occurance, so I am wondering if there is a design flaw or established pattern I am missing here that would help in this situation.





Aucun commentaire:

Enregistrer un commentaire