简体   繁体   English

oop检查返回类型是父类还是子类

[英]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: 和这个继承自Parent的类:

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

In some random class, I have a function that returns Parent: 在一些随机类中,我有一个返回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. 当我打电话给这个GetPerson时,我想知道它是父母还是孩子。 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. 我复制并粘贴了“if”语句,当人实际上是“Child”类型时它确实返回true。 Make sure that person's type is indeed of type child at the time you enter the if condition. 在输入if条件时,确保该人的类型确实是child类型。 This would presume that GetPerson(); 这会假设GetPerson(); always returns a parent. 总是返回父母。

Did you try GetType() and typeof() ? 你尝试过GetType()typeof()吗?

Example: 例:

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

Regards 问候

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

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