[英]How do you determine whether or not a given Type (System.Type) inherits from a specific base class (in .Net)?
这可能是一个简单的答案,我只是遗漏了一些东西,但是这里...如果我有一个Type,(即一个实际的System.Type ......不是一个实例)我该如何判断它继承自另一个特定的基类型?
使用System.Type类的IsSubclassOf方法。
One thing to clarify between Type.IsSubTypeOf()
and Type.IsAssignableFrom()
: 在
Type.IsSubTypeOf()
和Type.IsAssignableFrom()
之间澄清一件事:
IsSubType()
will return true
only if the given type is derived from the specified type. 仅当给定类型是从指定类型派生时,
IsSubType()
才会返回true
。 It will return false
if the given type IS the specified type. 如果给定类型是指定类型,它将返回
false
。
IsAssignableFrom()
will return true
if the given type is either the specified type or derived from the specified type. 如果给定类型是指定类型或从指定类型派生,则
IsAssignableFrom()
将返回true
。
So if you are using these to compare BaseClass
and DerivedClass
(which inherits from BaseClass
) then: 因此,如果您使用它们来比较
BaseClass
和DerivedClass
(继承自BaseClass
),那么:
BaseClassInstance.GetType.IsSubTypeOf(GetType(BaseClass)) = FALSE
BaseClassInstance.GetType.IsAssignableFrom(GetType(BaseClass)) = TRUE
DerivedClassInstance.GetType.IsSubTypeOf(GetType(BaseClass)) = TRUE
DerivedClassInstance.GetType.IsAssignableFrom(GetType(BaseClass)) = TRUE
EDIT: Note that the above solution will fail if the base type you are looking for is an interface. 编辑:请注意,如果您要查找的基本类型是接口,上述解决方案将失败。 The following solution will work for any type of inheritance, be it class or interface.
以下解决方案适用于任何类型的继承,无论是类还是接口。
// Returns true if "type" inherits from "baseType"
public static bool Inherits(Type type, Type baseType) {
return baseType.IsAssignableFrom(type)
}
(Semi)Helpful extract from the MSDN article: (半)来自MSDN文章的有用摘录:
true if [the argument] and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of [the argument], or if the current Type is an interface that [the argument] implements, or if [the argument] is a generic type parameter and the current Type represents one of the constraints of [the argument]. 如果[参数]和当前类型表示相同类型,或者当前类型位于[参数]的继承层次结构中,或者当前类型是[参数]实现的接口,或者如果[ argument]是泛型类型参数,当前Type表示[参数]的约束之一。 false if none of these conditions are true, or if [the argument] is a null reference (Nothing in Visual Basic).
如果这些条件都不为真,或者[参数]是空引用(在Visual Basic中为Nothing),则返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.