Something like:
public IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType)
{
return assembly.GetTypes().Where(t => baseType.IsAssignableFrom(t));
}
If you need to handle generics, that gets somewhat trickier (e.g. passing in the open List<>
type but expecting to get back a type which derived from List<int>
). Otherwise it's simple though :)
If you want to exclude the type itself, you can do so easily enough:
public IEnumerable<Type> FindDerivedTypes(Assembly assembly, Type baseType)
{
return assembly.GetTypes().Where(t => t != baseType &&
baseType.IsAssignableFrom(t));
}
Note that this will also allow you to specify an interface and find all the types which implement it, rather than just working with classes as Type.IsSubclassOf
does.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…