Is it possible to override a method with a derived parameter instead of a base one?

后端 未结 4 464
眼角桃花
眼角桃花 2020-12-15 23:37

I\'m stuck in this situation where:

  1. I have an abstract class called Ammo, with AmmoBox and Clip as chil
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 00:21

    You can use composition with interface extensions instead of multiple-inheritance:

    class Ammo {}
    class Clip : Ammo {}
    class AmmoBox : Ammo {}
    
    class Firearm {}
    interface IClipReloadable {}
    interface IAmmoBoxReloadable {}
    
    class ClipWeapon : Firearm, IClipReloadable, IAmmoBoxReloadable {}
    class AmmoBoxWeapon : Firearm, IAmmoBoxReloadable {}
    
    static class IClipReloadExtension {
        public static void Reload(this IClipReloadable firearm, Clip ammo) {}
    }
    
    static class IAmmoBoxReloadExtension {
        public static void Reload(this IAmmoBoxReloadable firearm, AmmoBox ammo) {}
    }
    

    So that you will have 2 definitions of Reload() method with Clip and AmmoBox as arguments in ClipWeapon and only 1 Reload() method in AmmoBoxWeapon class with AmmoBox argument.

    var ammoBox = new AmmoBox();
    var clip = new Clip();
    
    var clipWeapon = new ClipWeapon();
    clipWeapon.Reload(ammoBox);
    clipWeapon.Reload(clip);
    
    var ammoBoxWeapon = new AmmoBoxWeapon();
    ammoBoxWeapon.Reload(ammoBox);
    

    And if you try pass Clip to AmmoBoxWeapon.Reload you will get an error:

    ammoBoxWeapon.Reload(clip); // <- ERROR at compile time
    

提交回复
热议问题