逆变和协变

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo9
{
    class Program
    {
        static void Main(string[] args)
        {
            //协变
            IDAL<Animal> dal1 = new DAL<Animal>();
            IDAL<Person> dal2 = new DAL<Person>();
           dal1 = dal2;
           dal1.say();
            //逆变

           IDAL2<Animal> dal3 = new DAL2<Animal>();
           IDAL2<Person> dal4 = new DAL2<Person>();
           dal4 = dal3;
           dal4.say();

           Console.ReadLine();
      
        }
    }

    interface IDAL<out T> {

        T say();
    }

    class DAL<T>: IDAL<T> where T:new()
    {
     public T say() {
         Console.WriteLine("DAL1=" + typeof(T));
            return new T();
        }
    }

    interface IDAL2<in T>
    {

        void say();
    }

    class DAL2<T> : IDAL2<T> where T:new()
    {
        public void say()
        {
            T t = new T();
            Console.WriteLine("DAL2="+typeof(T));
            
        }
    }


    class Animal{
    
    }

    class Person:Animal
    {

    }
}
View Code

泛型不支持协变但支持逆变,接口和委托支持协变和逆变(包括泛型接口和委托)

原文地址:https://www.cnblogs.com/tiancai/p/6406861.html