简体   繁体   中英

How to have access to an inherited method in C#?

Am I missing any concept about inheritance? I am trying to call a method that is in a child class but it doesn't work.

This is what I have, so simple:

Vuelo.cs

 public class Vuelo
{
    private Aeronave _aeronave { get; set; }

    public Vuelo(string numero, Aeronave aeronave)
    {
        ValidarNumero(numero); // validates numero

        _aeronave = aeronave;
    }

    public string modelo_aeronave()
    {
        return _aeronave.model(); // This is where the error goes, .model()
    }

    public string RegistroAvion()
    {
        return _aeronave.Registration(); // This worked perfectly
    }
}

Aeronave.cs

 public class Aeronave
{
    private string _registration { get; set; }


    public Aeronave(string registration)
    {
        _registration = registration;
    }

    public string Registration()
    {
        return _registration;
    }

}

Airbus319.cs (the child class):

 public class AirbusA319 : Aeronave
{
    private string _model { get; set; }

    public AirbusA319(string model, string registro) : base(registro)
    {
        _model = model;

    }

    public string model()
    {
        return _model;
    }
}

I want to show up the model of the Airbus that is in model() like this:

Vuelo vuelo = new Vuelo("AB345", new AirbusA319("G-EUPT", "GG235"));
Console.WriteLine(vuelo.modelo_aeronave());

I can't find solutions in the inte.net, even in microsoft docs about inheritance.

You would need to modify your classes as shown below. Aeronave should contain model (virtual or abstract) to be overridden in Airbus.

public abstract class Aeronave
{
    private string _registration { get; set; }


    public Aeronave(string registration)
    {
        _registration = registration;
    }

    public string Registration()
    {
        return _registration;
    }
     public abstract string model();

}
public class AirbusA319 : Aeronave
{
    private string _model { get; set; }

    public AirbusA319(string model, string registro) : base(registro)
    {
        _model = model;

    }

    public override string model()
    {
        return _model;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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