How do I use composition with inheritance?

前端 未结 10 2388
星月不相逢
星月不相逢 2021-02-09 04:41

I\'m going to try to ask my question in the context of a simple example...

Let\'s say I have an abstract base class Car. Car has-a basic Engine object. I have a method

10条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-09 05:22

    You can use C# generics to get what you're looking for, here.

    The distinction of using generics is that your Ferrari "knows" that its Engine is-a TurboEngine, while the Car class doesn't have to know anything new—only that EngineType is-an Engine.

    class Program
    {
        static void Main(string[] args)
        {
            Ferrari ferarri = new Ferrari();
            ferarri.Start();
            ferarri.Boost();
        }
    }
    public class Car where EngineType : Engine, new()
    {
        protected EngineType engine;
    
        public Car()
        {
            this.CreateEngine();
        }
        protected void CreateEngine()
        {
            this.engine = new EngineType();
        }
        public void Start()
        {
            engine.Start();
        }
    }
    
    public class Ferrari : Car
    {
        public void Boost()
        {
            engine.Boost();
        }
    }
    
    public class Engine
    {
        public virtual void Start()
        {
            Console.WriteLine("Vroom!");
        }
    }
    public class TurboEngine : Engine
    {
        public void Boost()
        {
            Console.WriteLine("Hang on to your teeth...");
        }
        public override void Start()
        {
            Console.WriteLine("VROOOOM! VROOOOM!");
        }
    }
    

提交回复
热议问题