コード例 #1
0
 public void Tshow()
 {
     //协变:接口泛型参数加了个out,就是为了解决上述的问题
     {
         ICustomerListOut <Bird> customerList2 = new CustomerListOut <Sparrow>();
         customerList2.Get();/*有返回值*/
     }
     //逆变
     {
         ICustomerListIn <Sparrow> customerList1 = new CustomerListIn <Bird>();
         customerList1.Show(new Sparrow()
         {
             Id = 1, Name = "张三"
         });                                                       /*有参数*/
     }
     {
         IMyList <Sparrow, Bird> myList2 = new MyList <Sparrow, Sparrow>(); //协变
         IMyList <Sparrow, Bird> myList3 = new MyList <Bird, Bird>();       //逆变
         IMyList <Sparrow, Bird> myList4 = new MyList <Bird, Sparrow>();    //协变+逆变
     }
 }
コード例 #2
0
 public static void Show()
 {
     {
         Bird    parent1 = new Bird();
         Bird    parent2 = new Sparrow();
         Sparrow child   = new Sparrow();
     }
     {
         List <Bird> birdList = new List <Bird>();
         //List<Bird> birdList1 = new List<Sparrow>();//两个list泛型实例不存在继承关系,
         //每只麻雀都是一只鸟,但是list不知道,需要强制去转
         List <Bird> birdList2 = new List <Sparrow>().Select(c => (Bird)c).ToList();//把每一只麻雀转换为bird
     }
     {
         IEnumerable <Bird> birdList1 = new List <Bird>();
         IEnumerable <Bird> birdList2 = new List <Bird>();
     }
     {
         ICustomerListOut <Bird> customerList  = new CustomerListOut <Bird>();
         ICustomerListOut <Bird> customerList1 = new CustomerListIn <Sparrow>();
     }
 }