问题描述
假设我有一个类,它看起来像这样:
Suppose I have a class that looks like this:
class Derived : // some inheritance stuff here
{
}
我要检查这样的事情在我的code:
I want to check something like this in my code:
Derived is SomeType;
不过貌似是
派生是变量类型Dervied运营商的需要,不是派生本身。
我不想创建派生类型的对象。结果
如何我确保衍生继承 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。如果有帮助,我想是什么,其中
关键字做泛型。结果
修改结果
类似答案,但它检查的对象。我要检查类本身。
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.
推荐答案
要检查是否有可转让性,可以使用方法:
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.
要检查是否有严格的继承,你可以使用<$c$c>Type.IsSubclassOf$c$c>:
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
这篇关于如何检查是否一个类继承另一个类没有实例呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!