简体   繁体   中英

Using constructor of inherited class in constructor

I'm new to C# and I am trying to create a constructor that uses a constructor of the base class. I need to set the values of Engine Class within Constructor of Car class.

Here's what I have now:

public Car (double brand, double model, double engineCap, double fuelCount, double fuelCap )
: base (SetEngine(engineCap, fuelCount, fuelCap))
    {
        this.brand = brand;
        this.model = model;

    }

    private static Engine SetEngine(double engineCap, double fuelCount, double fuelCap)
    {
        Engine engine = new Engine(engineCap, fuelCount, fuelCap);
        return engine;
    }
}

My implementation is probably wrong here. Here's the constructor of the base class:

  public Engine(double engineCap, double fuelCount, double fuelCap)
  {
      this.engineCap = engineCap;
      this.fuelCount = fuelCount;
      this.fuelCap = fuelCap;
  }

The base class of Car is Engine.

Just call the base class constructor with the parameters it expects:

public Car (double brand, double model, double engineCap, double fuelCount, double fuelCap ) 
    : base (engineCap, fuelCount, fuelCap)
{
    this.brand = brand;
    this.model = model;
}

Create instance of Engine first and then pass it as argument to car. or create engine instance in car itself and assign to protected member of base class.

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