简体   繁体   中英

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() :

  • IsSubType() will return true only if the given type is derived from the specified type. It will return false if the given type IS the specified type.

  • IsAssignableFrom() will return true if the given type is either the specified type or derived from the specified type.

So if you are using these to compare BaseClass and DerivedClass (which inherits from BaseClass ) then:

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:

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]. false if none of these conditions are true, or if [the argument] is a null reference (Nothing in Visual Basic).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM