找到所有类型的父(包括基类和接口) [英] Find all parent types (both base classes and interfaces)
问题描述
我希望能够找到所有父类型(基类和接口)为特定类型。
I want to be able to find all parent types (base classes and interfaces) for a specific type.
例如,如果我有
class A : B, C { }
class B : D { }
interface C : E { }
class D { }
interface E { }
我希望看到A 是的BCD和E对象
i want to see that A is B C D and E and Object
最新最好的方式做到这一点?有没有反射法做到这一点还是需要让自己的东西。
Whats the best way to do this? is there a reflection method to do this or do i need to make myself something.
==== ====编辑
====EDIT====
因此,像这样?
public static IEnumerable<Type> ParentTypes(this Type type)
{
foreach (Type i in type.GetInterfaces())
{
yield return i;
foreach (Type t in i.ParentTypes())
{
yield return t;
}
}
if (type.BaseType != null)
{
yield return type.BaseType;
foreach (Type b in type.BaseType.ParentTypes())
{
yield return b;
}
}
}
我有点希望我没T要做自己,但哦。
I was kinda hoping i didn't have to do it myself but oh well.
推荐答案
要一个类型得到实现的接口,使用的 Type.GetInterfaces
。要看到它的类层次结构,可以使用 Type.BaseType
反复,直到你打一个空
-reference(通常你击中后会出现这种情况 System.Object的
,但不一定 - 例如,一个接口类型的基本类型将直接空
)
To get the interfaces implemented by a type, use Type.GetInterfaces
. To see its class-hierarchy, you can use Type.BaseType
iteratively until you hit a null
-reference (typically this will happen after you hit System.Object
, but not necessarily - for example, an interface-type's base type will directly be null
).
这篇关于找到所有类型的父(包括基类和接口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!