泛型协变与逆变

  C#显式变化使用IN和OUT关键字只适用于委托和接口,不适用于类、结构和方法。

下面是笔者制作的学习代码,特别有助于理解C#中的协变与逆变。

//空间
namespace ConsoleApplication1
{
     //基类
    class Animal { public int legs = 4; public string Name = "tomhuy"; };
     //继承类
    class Dog : Animal {  }
     //协变委托
    delegate T Factry<out T>();
     //逆变委托
    delegate void Action1<in T>(T a);
     //协变接口
    interface IMyIfc<out T> { T GetFirst(); }
     //继承接口类
    class SimpleReturn<T>: IMyIfc<T>
    {
        public T[] items = new T[2];
        public T GetFirst() { return items[0]; }
    }
      //主程序
    class Program
    {
         //静态函数
        static Dog MakeDog() { return new Dog(); }
         //静态空函数
        static void MakeAnimal(Animal a) { Console.WriteLine(a.legs); }
         //静态空函数
        static void DoSomething(IMyIfc<Animal> returner)
        {
            Console.WriteLine(returner.GetFirst().Name);
        }
         //主程序入口
        static void Main(string[] args)
        {
             
             //协变委托实例
            Factry<Dog> dogMake = MakeDog;
            Factry<Animal> animalMake = dogMake;
             //逆变委托实例
            Action1<Animal> makeanimal = MakeAnimal;
            Action1<Dog> makedog = makeanimal;
             //接口协变实例
            SimpleReturn<Dog> dogReturn = new SimpleReturn<Dog>();
            dogReturn.items[0] = new Dog() { Name = "zhangshan" };
            IMyIfc<Animal> animalReturn = dogReturn;
             //控制台协变输出
            Console.WriteLine(dogMake().legs.ToString());
            Console.WriteLine(animalMake().legs.ToString());
             //控制台逆变输出
            makedog(new Dog());
            makeanimal(new Animal());
            makeanimal(new Dog());
             //控制台协变输出
            DoSomething(dogReturn);
        }
    }
}


Comments (1) -

12/2/2019 3:09:12 PM #

is\as\IEnumerable<T> also to convariance(contravariance)

风信子 People's Republic of China

Add comment

  Country flag

biuquote
微笑得意调皮害羞酷大笑惊讶发呆喜欢可怜尴尬闭嘴噘嘴皱眉伤心抓狂呕吐坏笑漫骂发怒
Loading

Calendar

<<  January 2020  >>
MonTueWedThuFriSatSun
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789

切换到大日历中浏览

Month List

声明

本博所有网友评论不代表本博立场,版权归其作者所有。

© Copyright 2011

 

Powered by BlogYi.NET ver:2.5.0.10, original powered by BlogEngine.NET.