mardi 13 juin 2017

Design pattern for filtering to specific types?

After deserialization, I have a collection MyCollection of object instances, the specific type of which derive from some BaseClass. This collection is fed into a process that is sensitive (using reflection) to the specific derived type: one set of content is called if the process is fed an IEnumerable<DerivedTypeA> (where DerivedTypeA derives from BaseClass), whereas another is called if the process is fed an IEnumerable<DerivedTypeB>. If I feed the process an IEnumerable<BaseClass>, the resulting reflection can't find the corresponding method/classes to use, and the code errors out.

I initially thought that I could use MyCollection.OfType<BaseClass>(), but the reflection code seems to think that BaseClass is the actual type, so that attempt doesn't work. I could go through and set up filters for each derived type, handling each resulting collection in turn:

var instancesTypeA = MyCollection.OfType<DerivedTypeA>();
var instancesTypeB = MyCollection.OfType<DerivedTypeB>();

However, this is pretty clumsy and requires me to update the class each time I add a new type deriving from BaseClass. I feel like there should be a design pattern or some way to handle this scenario without violating the open/closed principle and without creating a bunch of derivative classes. What am I missing?

Aucun commentaire:

Enregistrer un commentaire