1

假设我们有 2 个类。第一个是人

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

第二个是老师

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}

我想在列表中添加老师

Teacher teacher = new Teacher() {FirstName="Peter", LastName="Janson",Position="boss" };
            List <Person> people= new List<Person> { };
            people.Add(teacher);

当这个列表是类型并且人只有名字和姓氏属性并且“老师”也有位置属性时,我怎么可能在列表中添加老师?

4

2 回答 2

8

This is a question about the fundamental object oriented concept called polymorphism. A Teacher is a Person, but your list of Person instances only knows that it contains a list of Person instances; it doesn't know anything about classes that derive from Person, nor does it need to.

If you are working with elements in your list, you can determine their type, and then cast them into that type like so:

foreach (Person x in people)
{
    if (x is Teacher)
    {
        Teacher y = (Teacher) x;
    }
}

Then you can access the properties of teacher: y.Position.

于 2017-03-31T13:15:20.843 回答
8

根据您之前的问题,我认为您在理解多态性方面遇到了一些问题。

尝试将继承视为汽车和车辆之间的关系。车辆是基础类型,汽车、摩托车、飞机、卡车等是派生类型。

public class Vehicle
{
    public string Model {get;set;}
}

想象一下你有一个飞机库:

List<Vehicle> hangar = new List<Vehicle>();

您可以在飞机库中停放多辆不同的车辆,因为它非常大:

hangar.Add(new Plane());
hangar.Add(new Car());

尽管它们是不同的类型,但它们仍然继承自车辆,因此可以将它们存储为车辆。

问题是,飞机有机翼,汽车没有。如果您只乘坐第一辆车hangar[0],您就知道它是一辆车,并且您可以获得关于它的基本信息(所有车辆共有的信息):,hangar[0].Model但如果您要访问的车辆类型,您必须更具体想要更详细的信息。

现在,由于您可能不知道它是什么类型的车辆,您需要检查:

if (hangar[0] is Car)
{
    string registrationNumber = ((Car)hangar[0]).RegistrationNumber;
}
else if (hangar[0] is Plane)
{
    int numberOfWings = ((Plane)hangar[0]).NumberOfWings;
}

使用 C#7 语法,您还可以使用以下简化形式:

if (hangar[0] is Car car)
{
    string registrationNumber = car.RegistrationNumber;
}
else if (hangar[0] is Plane plane)
{
    int numberOfWings = plane.NumberOfWings;
}

与现实生活的类比是,如果你进入机库,你必须看看汽车在哪里,飞机在哪里。这里也一样。

多态性使您可以将许多派生类视为它们的公共基础。在您的个人示例中,如果您希望能够按姓名搜索某人,这将很有用。老师是人,医生也是人,他们都是人,都有名字,所以在那种情况下你可以对他们一视同仁。

把它想象成快速约会——你去,你会遇到人。你先做什么?你问对方的名字。然后你问“你以什么为生?” 他们说“我是老师”或“我是医生”。现在你知道他们是什么类型了,你可以问他们“你教什么?” 或“您专攻哪个医学分支?”

我希望这能让你更清楚:-)

于 2017-03-31T13:21:42.827 回答