为什么 Person p = new Student() 给出学生类型

Why does Person p = new Student() gives student type

愚蠢的问题。于是就有了代码:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void Method()
    {
        Console.WriteLine("Hello, I'm person!");
    }
}

class Student : Person 
{
    //
}

主要

Student student = new Student();
Person p = student;
Console.WriteLine(p.GetType()); // Student

为什么这个 return 是 Student?我认为它应该是 Person,因为我们创建了 Person 实例并插入其中 Student 对象

即使 P 的类型是 Person,它也是对 student 的引用。当您实例化 Student 对象时,您的 P 变量只是指学生对象。