简体   繁体   中英

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?

The is operator does this.

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.IsSubclassOf

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

Use Type.IsAssignableFrom :

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

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