2010-04-01 85 views

回答

3

可以使用Type.BaseType从顶级类型遍历到最基类型,直到基类型达到object

事情是这样的:

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)); 
} 
0

我用这个代码来获得一个继承的类型定义的所有类。它搜索所有加载的程序集。有用的,如果你只有基类,你会得到扩展基类的所有类。

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(); 
}