检查一个 System.Type 对象是否派生自另一个 System.Type 对象

本文关键字:对象 Type System 是否 派生 另一个 一个 检查 | 更新日期: 2023-09-27 18:36:54

var type1 = typeof (ClassA);
var type2 = typeof (ClassB);

type2是从type1派生出来的吗?

bool isDerived = // code....

检查一个 System.Type 对象是否派生自另一个 System.Type 对象

var type1 = typeof(ClassA);
var type2 = typeof(ClassB);
bool isDerived = type2.IsSubClassOf(type1);

参考:类型.Is子类的方法

您可以查看Type.Basetype(请参阅此处)以查看您继承的类型。

所以你可以写这样的东西:

bool isDerived = type2.BaseType == type1;

感谢丹尼尔指出我的typeof错误!

如果你的目的是检查Type2是从Type1派生的类,则Type.IsSubclassOf方法可能是合适的。 它返回 true:

如果 C 参数表示的 Type 和当前 Type 表示类

,并且当前 Type 表示的类派生自 C 表示的类;否则为 false。如果 c 和当前 Type 表示同一类,则此方法也返回 false。

在您的示例中,isDerived可以表示为:

isDerived = type2.IsSubclassOf(type1)
void Main()
{
    var type1 = typeof (ClassA);
    var type2 = typeof (ClassB);
    bool b = type1.IsAssignableFrom(type2);
    Console.WriteLine(b);
}
    class ClassA {}
    class ClassB : ClassA {}

IsAssignableFrom 的行为

如果 c 和当前类型表示相同的类型,或者如果 当前类型位于 c 的继承层次结构中,或者如果当前 类型是 c 实现的接口,或者如果 c 是泛型类型 参数和当前类型表示 c 的约束之一, 或者如果 c 表示值类型,而当前类型表示 Nullable (Visual Basic 中的 Nullable(of c))。如果这些都不是,则为 false。 条件为 true,或者如果 c 为 null。