Covariance and contravariance real world example

后端 未结 9 1994
醉梦人生
醉梦人生 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:35

    Here's what I put together to help me understand the difference

    public interface ICovariant { }
    public interface IContravariant { }
    
    public class Covariant : ICovariant { }
    public class Contravariant : IContravariant { }
    
    public class Fruit { }
    public class Apple : Fruit { }
    
    public class TheInsAndOuts
    {
        public void Covariance()
        {
            ICovariant fruit = new Covariant();
            ICovariant apple = new Covariant();
    
            Covariant(fruit);
            Covariant(apple); //apple is being upcasted to fruit, without the out keyword this will not compile
        }
    
        public void Contravariance()
        {
            IContravariant fruit = new Contravariant();
            IContravariant apple = new Contravariant();
    
            Contravariant(fruit); //fruit is being downcasted to apple, without the in keyword this will not compile
            Contravariant(apple);
        }
    
        public void Covariant(ICovariant fruit) { }
    
        public void Contravariant(IContravariant apple) { }
    }
    

    tldr

    ICovariant apple = new Covariant(); //because it's covariant
    IContravariant fruit = new Contravariant(); //because it's contravariant
    

提交回复
热议问题