linq中的逆变和协变

案列:

 public class Animal { }
    public class Dog : Animal { }

    class Program
    {
        static void Main(string[] args)
        {
            Animal dog = new Dog();
            Dog dog1 = new Dog();


            List<Dog> dogs = new List<Dog>();
            //List<Animal> animals = dogs;
            List<Animal> animals = dogs.Select(d => (Animal)d).ToList();
            // out是协变,输出类型,作为结果返回
            // in是逆变,输入类型,作为参数
            // IEnumerable<out T> 这个T是输出类型,传入的是dog,可以协变为Animal。
            IEnumerable<Animal> animals1 = dogs;
            // Action<in T>(T obj);
            Action<Animal> actionAnimal = new Action<Animal>(a => { });
            Action<Dog> actionDog = actionAnimal;
            actionDog(dog1);


            Console.ReadKey();
        }

 

posted @ 2021-11-18 23:11  vba是最好的语言  阅读(19)  评论(0编辑  收藏  举报