How to get Type[] of all classes a class extends
You can do Type[] interfaces = typeof(MyClass).GetInterfaces();
to get a list of everything a class implements implements.
I am wondering if there is anyway to crawl the "extends" tree to see all the base types a class inherits, i.e开发者_运维知识库. abstract classes etc.?
You can use Type.BaseType
to traverse from the top-level type to the most base type until the base type reaches object
.
Something like this:
abstract class A { }
class B : A { }
class C : B { }
public static void Main(string[] args)
{
var target = typeof(C);
var baseTypeNames = GetBaseTypes(target).Select(t => t.Name).ToArray();
Console.WriteLine(String.Join(" : ", baseTypeNames));
}
private static IEnumerable<Type> GetBaseTypes(Type target)
{
do
{
yield return target.BaseType;
target = target.BaseType;
} while (target != typeof(object));
}
I use this code to get all classes that inherits a defined Type. It searches all loaded Assemblies. Usefull if you have only the Baseclass and you will get all Classes that Extends the Baseclass.
Type[] GetTypes(Type itemType) {
List<Type> tList = new List<Type>();
Assembly[] appAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly a in appAssemblies) {
Module[] mod = a.GetModules();
foreach (Module m in mod) {
Type[] types = m.GetTypes();
foreach (Type t in types) {
try {
if (t == itemType || t.IsSubclassOf(itemType)) {
tList.Add(t);
}
}
catch (NullReferenceException) { }
}
}
}
return tList.ToArray();
}
精彩评论