简体   繁体   中英

oop Check if return type is parent or child class

Suppose I have this class:

public class Parent
{
    public string Name {get; set;}
}

and this class, which inherits from Parent:

public class Child : Parent
{
    public string Toys {get; set;}
}

In some random class, I have a function that returns Parent:

public class SomeClass
{
    public Parent GetPerson()
    {
      if (whatever)
      {
        return new Parent { Name = 'Parent' };
      }
      else
      {
        return new Child {Name = 'Child', Toys = 'Paper Plane, Spider Man'};
      }
    }
}

when I call this GetPerson, I want to know if it is a Parent or a Child. I thought this might work, but this condition is always false

var person = GetPerson();

if (person is Child childPerson) // This is always false :(
{
   var toys = childPerson.Toys;
}

I copied and pasted the "if" statement and it does return true when person is in fact "Child" type. Make sure that person's type is indeed of type child at the time you enter the if condition. This would presume that GetPerson(); always returns a parent.

Did you try GetType() and typeof() ?

Example:

if (person.GetType() == typeof(Child))
{
   ...
}

Regards

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