一种避免构造函数中的虚拟调用的方法

Vit*_*lyB 2 c# oop

考虑以下示例中的代码:

abstract class Car
{
    public abstract Engine CarEngine { get; protected set; }

    public Car()
    {
        CarEngine.EngineOverheating += new EventHandler(CarEngine_EngineOverheating);
    }

    void CarEngine_EngineOverheating(object sender, EventArgs e)
    {
        // Subscribing to the event of all engines
    }
}

sealed class Toyota : Car
{
    public Toyota()
    {
        this.CarEngine = new ToyotaEngine();
    }


    public override Engine CarEngine { get; protected set; }
}

abstract class Engine
{
    public event EventHandler EngineOverheating;
}

class ToyotaEngine : Engine
{

}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,此代码不起作用,因为CarEngine尚未初始化.我有什么选择来解决这种情况?

我看到他们的缺点有几种选择:

  1. 手动订阅每个子类 - 结果包含大量的样板代码,因此容易出错.
  2. Initialize()函数 - 容易出错且冗余.

我很乐意看到更多的想法.

谢谢!

Pol*_*ity 7

在Car中创建构造函数,将引擎作为参数并在订阅事件之前分配它,如下所示:

abstract class Car
{
    public abstract Engine CarEngine { get; protected set; }

    public Car(Engine carEngine)
    {
        CarEngine = carEngine;
        CarEngine.EngineOverheating += new EventHandler(CarEngine_EngineOverheating);
    }

    void CarEngine_EngineOverheating(object sender, EventArgs e)
    {
        // Subscribing to the event of all engines 
    }
}

sealed class Toyota : Car
{
    public Toyota()
        : base(new ToyotaEngine())
    {
    }


    public override Engine CarEngine { get; protected set; }
}
Run Code Online (Sandbox Code Playgroud)