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(); }