Multiple Inheritance in C#

后端 未结 15 1975
醉酒成梦
醉酒成梦 2020-11-22 03:03

Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.

15条回答
  •  日久生厌
    2020-11-22 03:17

    Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel, IBrakable implies a property of type BrakePedal, etc.

    Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg:

    public interface ISteerable { SteeringWheel wheel { get; set; } }
    
    public interface IBrakable { BrakePedal brake { get; set; } }
    
    public class Vehicle : ISteerable, IBrakable
    {
        public SteeringWheel wheel { get; set; }
    
        public BrakePedal brake { get; set; }
    
        public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }
    }
    
    public static class SteeringExtensions
    {
        public static void SteerLeft(this ISteerable vehicle)
        {
            vehicle.wheel.SteerLeft();
        }
    }
    
    public static class BrakeExtensions
    {
        public static void Stop(this IBrakable vehicle)
        {
            vehicle.brake.ApplyUntilStop();
        }
    }
    
    
    public class Main
    {
        Vehicle myCar = new Vehicle();
    
        public void main()
        {
            myCar.SteerLeft();
            myCar.Stop();
        }
    }
    

提交回复
热议问题