Covariance and contravariance real world example

后端 未结 9 2003
醉梦人生
醉梦人生 2020-11-22 16:57

I\'m having a little trouble understanding how I would use covariance and contravariance in the real world.

So far, the only examples I\'ve seen have been the same o

9条回答
  •  暖寄归人
    2020-11-22 17:48

    // Contravariance
    interface IGobbler {
        void gobble(T t);
    }
    
    // Since a QuadrupedGobbler can gobble any four-footed
    // creature, it is OK to treat it as a donkey gobbler.
    IGobbler dg = new QuadrupedGobbler();
    dg.gobble(MyDonkey());
    
    // Covariance
    interface ISpewer {
        T spew();
    }
    
    // A MouseSpewer obviously spews rodents (all mice are
    // rodents), so we can treat it as a rodent spewer.
    ISpewer rs = new MouseSpewer();
    Rodent r = rs.spew();
    

    For completeness…

    // Invariance
    interface IHat {
        void hide(T t);
        T pull();
    }
    
    // A RabbitHat…
    IHat rHat = RabbitHat();
    
    // …cannot be treated covariantly as a mammal hat…
    IHat mHat = rHat;      // Compiler error
    // …because…
    mHat.hide(new Dolphin());      // Hide a dolphin in a rabbit hat??
    
    // It also cannot be treated contravariantly as a cottontail hat…
    IHat cHat = rHat;  // Compiler error
    // …because…
    rHat.hide(new MarshRabbit());
    cHat.pull();                   // Pull a marsh rabbit out of a cottontail hat??
    

提交回复
热议问题