简体   繁体   English

如果子类型是父类型

[英]If child type is type of parent

I am trying to pass a an inherited class type in to a method and want to check if the type is a type of base class. 我试图将一个继承的类类型传递给一个方法,并希望检查该类型是否是一种基类。 How can I do this, since inherited.GetType() == typeof(baseclass) will return false? 我怎么能这样做,因为inherited.GetType()== typeof(baseclass)会返回false?

The is operator does this. is运营商做到这一点。

if (inherited is baseclass)
{
    // do stuff
}

You could also use Type.BaseType if you want to know that it is exactly the direct parent. 如果您想知道它正是直接父级,您也可以使用Type.BaseType

您也可以使用Type.IsSubclassOf

inherited.GetType().IsSubclassOf(typeof(Base));

Use Type.IsAssignableFrom : 使用Type.IsAssignableFrom

if (typeof(baseclass).IsAssignableFrom(inh.GetType())
{
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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