在构造函数中使用继承类的构造函数

时间:2016-04-20 19:11:10

标签: c#

我是C#的新手,我正在尝试创建一个使用基类构造函数的构造函数。我需要在Car类的Constructor中设置Engine Class的值。

这就是我现在所拥有的:

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

我的实施可能在这里错了。这是基类的构造函数:

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

Car的基类是Engine。

2 个答案:

答案 0 :(得分:3)

使用它期望的参数调用基类构造函数:

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

答案 1 :(得分:0)

首先创建Engine的实例,然后将其作为参数传递给car。或者在汽车本身创建引擎实例并分配给受保护的基类成员。