C# List<T> adding inherited items [closed]

僤鯓⒐⒋嵵緔 提交于 2019-12-12 04:12:36

问题


Let's say that we have 2 classes. The first one is Person

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; }
    }
}

The second one is Teacher

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; }
    }
}

And I want to add in a List the teacher

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

How is it possible that I add the teacher in the list when this list is of type and person only has FirstName and LastName properties and the "teacher" has also a Position property?


回答1:


Based on your previous question, I think you're having some issues understanding polymorphism.

Try to think of inheritance as the relationship between cars and vehicles. A vehicle is a base type, and a car, a motorbike, a plane, a truck, etc. is a derived type.

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

Imagine you have an aeroplane hangar:

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

You can park multiple different vehicles in an aeroplane hangar because it's very big:

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

Although they're different types, they still inherit from vehicle, so they can be stored as vehicles.

The thing is, planes have wings and cars don't. If you just take the first vehicle hangar[0], you know it's a vehicle and you can get the basic information about it (information that's common to all vehicles): hangar[0].Model, but you have to be more specific about the type of vehicle you're accessing if you want more detailed information.

Now, since you might not know what type of vehicle it is, you need to check:

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

Using the C#7 syntax you can also use this simplified form:

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

The analogy with real life is that if you enter the hangar, you have to look to see where the car is, and where the plane is. It's the same here.

Polymorphism lets you treat many derived classes as their common base. In your person example, this would be useful if you wanted to be able to search for someone by name. A teacher is a person, a doctor is a person, they are all people and they all have names, so in that situation you can treat them the same.

Think of it like speed dating - you go and you meet people. What do you do first? You ask the other person's name. Then you ask "What do you do for a living?" and they say "I'm a teacher" or "I'm a doctor". Now you know what type they are, and you can ask them "What do you teach?" or "What branch of medicine do you specialise in?"

I hope this makes it clearer for you :-)




回答2:


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.



来源:https://stackoverflow.com/questions/43141525/c-sharp-listt-adding-inherited-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!