I once used this Linq-method to get all types inheriting from a base type B:
var listOfBs = (
from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
// alternative: from domainAssembly in domainAssembly.GetExportedTypes()
from assemblyType in domainAssembly.GetTypes()
where typeof(B).IsAssignableFrom(assemblyType)
// alternative: where assemblyType.IsSubclassOf(typeof(B))
// alternative: && ! assemblyType.IsAbstract
select assemblyType).ToArray();
EDIT: As this still seems to get more rep (thus more views), let me add some more details:
- As the above-mentioned link states, this method uses Reflection on each call. So when using the method repeatedly for the same type,
one could probably make it much more efficient by loading it once.
- As Anton suggests, maybe you could (micro)optimize it using
domainAssembly.GetExportedTypes()
to retrieve only publicly visible types (if that's all you need).
- As Noldorin mentions,
Type.IsAssignable
will also get the original (non-derived) type. (Type.IsSubclassOf
will not, but Type.IsSubclassOf
will not work if the base type is an interface).
- One may want/need to check for a 'real' class:
&& ! assemblyType.IsAbstract
. (Note that all interfaces are considered abstract, see MSDN.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…