c# - Exemples simples de co et de contrevariance

Mots clés : c#.netcovariancecontravarianceinvariantsc#

meilleur 2 Réponses c# - Exemples simples de co et de contrevariance

vote vote

95

void FeedTheAnimals(IEnumerable<Animal> animals)  {      foreach(Animal animal in animals)         animal.Feed(); } ... List<Giraffe> giraffes = ...; FeedTheAnimals(giraffes); 
void DoSomethingToAFrog(Action<Frog> action, Frog frog) {     action(frog); } ... Action<Animal> feed = animal=>{animal.Feed();} DoSomethingToAFrog(feed, new Frog()); 
void ReadAndWrite(IList<Mammal> mammals) {     Mammal mammal = mammals[0];     mammals[0] = new Tiger(); } 
vote vote

80

IList<string> strlist = new List<string>(); 
IList<IList<string>> strlists = new List<List<string>>(); 
IEnumerable<IList<string>> strlists = new List<List<string>>(); 

Questions similaires