c# - Get all last descendants of a base type? -
this question opposite of how find types direct descendants of base class?
if inheritance hierarchy have,
class base { } class derived1 : base { } class derived1a : derived1 { } class derived1b : derived1 { } class derived2 : base { }
i need mechanism find sub types of base
class in particular assembly @ end of inheritance tree. in other words,
subtypesof(typeof(base))
should give me
-> { derived1a, derived1b, derived2 }
this have come with. not sure if more elegant/efficient solutions exist..
public static ienumerable<type> getlastdescendants(this type t) { if (!t.isclass) throw new exception(t + " not class"); var subtypes = t.assembly.gettypes().where(x => x.issubclassof(t)).toarray(); return subtypes.where(x => subtypes.all(y => y.basetype != x)); }
and sake of completeness, repost answer direct descendants given here
public static ienumerable<type> getdirectdescendants(this type t) { if (!t.isclass) throw new exception(t + " not class"); return t.assembly.gettypes().where(x => x.basetype == t); }
Comments
Post a Comment