如何在不实例化的情况下检查一个类是否继承了另一个类? [英] How to check if a class inherits another class without instantiating it?
问题描述
假设我有一个看起来像这样的类:
Suppose I have a class that looks like this:
class Derived : // some inheritance stuff here
{
}
我想在我的代码中检查类似的东西:
I want to check something like this in my code:
Derived is SomeType;
但是看起来 is
运算符需要 Derived 是 Dervied 类型的变量,而不是 Derived 本身.我不想创建派生类型的对象.
如何确保 Derived 继承 SomeType
而不实例化它?
But looks like is
operator need Derived to be variable of type Dervied, not Derived itself.
I don't want to create an object of type Derived.
How can I make sure Derived inherits SomeType
without instantiating it?
P.S. 如果有帮助,我想要一些类似于 where
关键字对泛型的作用.
类似于 this 答案,但它正在检查一个对象.我想检查课程本身.
P.S. If it helps, I want something like what where
keyword does with generics.
Similar to this answer, but it's checking an object. I want to check the class itself.
推荐答案
要检查可分配性,您可以使用 Type.IsAssignableFrom
方法:
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
这将如您对类型相等、继承关系和接口实现所期望的那样工作,但不是当您在寻找跨显式/隐式转换运算符的可赋值性"时.
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
要检查严格继承,您可以使用Type.IsSubclassOf
:
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
这篇关于如何在不实例化的情况下检查一个类是否继承了另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!