c# - oop 检查返回类型是父类还是子类

标签 c# oop inheritance

假设我有这门课:

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

这个类继承自Parent:

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

在一些随机类中,我有一个返回 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'};
      }
    }
}

当我调用这个 GetPerson 时,我想知道它是父项还是子项。 我认为这可能有效,但这个条件总是错误的

var person = GetPerson();

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

最佳答案

我复制并粘贴了“if”语句,当人实际上是“Child”类型时,它确实返回 true。确保在输入 if 条件时该人的类型确实是 child 类型。这假设 GetPerson();总是返回一个父级。

关于c# - oop 检查返回类型是父类还是子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747514/

相关文章:

c# - .NET gmail API 身份验证(无需用户交互)

c# - 基于标签和地理位置的 Instagram 提要

c# - Microsoft AntiXSS - 是否需要解码?

oop - 哪个类(class)设计更好?

c# - 为 IList 优化 LINQ

c++ - 库管理对象的生命周期,使用智能指针还是原始的?

javascript - 在同级兄弟指令中进行通信的理想方式是什么?

java - 协变结构因 Java 中的捕获错误而失败

css - 如何使CSS中的内部UL列表不继承外部UL列表

c# - C# 中的静态类列表