简体   繁体   中英

ClassB inherits ClassA. How do I check if ClassA objA is of ClassB type and then convert objA to ClassB?

Say that ClassB inherits ClassA, and that I have an object named objA that is of type ClassA. How do I check if objA is of ClassB type and then convert objA to ClassB?

You can do this:

var objB = objA as ClassB;
if (objB != null)
{
    // objA is of type ClassB, you can use it via objB
}

Or, if you're using C# 7:

if (objA is ClassB objB)
{
    // objA is of type ClassB, you can use it via objB
}

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