您可以使用Type[] interfaces = typeof(MyClass).GetInterfaces();
来获取类实现的所有类的列表。如何获得一个类扩展的所有类的类型[]
我想知道是否有无论如何抓取“扩展”树来查看类继承的所有基类型,即抽象类等?
您可以使用Type[] interfaces = typeof(MyClass).GetInterfaces();
来获取类实现的所有类的列表。如何获得一个类扩展的所有类的类型[]
我想知道是否有无论如何抓取“扩展”树来查看类继承的所有基类型,即抽象类等?
可以使用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));
}
我用这个代码来获得一个继承的类型定义的所有类。它搜索所有加载的程序集。有用的,如果你只有基类,你会得到扩展基类的所有类。
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();
}