Monday, 9 September 2013

How can you programmatically find the deepest common base type from a bunch of subclasses?

How can you programmatically find the deepest common base type from a
bunch of subclasses?

Given a collection of disparate objects, is it possible to find the
most-specific base class they all share?
For instance, given objects with these class hierarchies...
object -> Vehicle -> WheeledVehicle -> Car -> SportsCar
object -> Vehicle -> WheeledVehicle -> Bus
object -> Vehicle -> WheeledVehicle -> MotorCycle
object -> Vehicle -> WheeledVehicle -> Tricycle -> BigWheel
object -> Vehicle -> WheeledVehicle -> Tricycle -> Green Machine
(For fun...
http://www.wired.com/autopia/2011/03/green-machine-bike-is-a-big-wheel-for-grownups)
Is it possible to write a function with this signature...
public Type GetCommonBaseType(List<object> objects)
{
...
};
...and have it return 'WheeledVehicle'?
My thinking is to somehow build up lists of inheritance chains for each
object, reverse them so they all start with 'object', then walk down each
of them checking for a match across all lists. If any of the items don't
match, then the step before is your deepest matching base type.
However, I'm not sure how to go about building up the chain since 'base'
is an internal member. Is this something you can use Reflection to
determine?

No comments:

Post a Comment