Covariance vs. contravariance with respect to class inheritance

后端 未结 4 2341
猫巷女王i
猫巷女王i 2021-02-09 14:00

What is the meaning of the concepts \'covariance\' and \'contravariance\'?

Given 2 classes, Animal and Elephant (which inherits from

4条回答
  •  萌比男神i
    2021-02-09 14:25

    public interface IGoOut
    {
        T Func();
    }
    public interface IComeIn
    {
        void Action(T obj);
    }
    public class GoOutClass:IGoOut
    {
        public T Func()
        {
            return default(T);
        }
    }
    
    public class ComeInClass : IComeIn
    {
        public void Action(T obj) {  }
    }
    
    ==========================================================
    object obj = null;
    //Covariance Example [Array +  IEnumerable +  IEnumerator  +  IInterface  +  Func]
    object[] array = (string[]) obj;
    IEnumerable enumerable = (IEnumerable) obj;
    IEnumerator enumerator = (IEnumerator)obj;
    IGoOut goOut = (GoOutClass)obj;
    Func func = (Func)obj;
    
    
    //Contravariance Example[IInterface]
    IComeIn comeIn = (ComeInClass) obj;
    
        

    提交回复
    热议问题