fork(1) download
  1. using System.IO;
  2. using System;
  3. using System.Collections.Generic;
  4.  
  5. class Fruit
  6. {
  7. public void Eat()
  8. {
  9. Console.WriteLine("You ate fruit!");
  10. }
  11. }
  12.  
  13. class Orange : Fruit {}
  14.  
  15. class Program
  16. {
  17. static void Main()
  18. {
  19. // создаём объект делегата, который принимает фрукт и возвращает void
  20. Action<Fruit> actionWithFruit = fruit => fruit.Eat();
  21.  
  22. // создаём список из трёх апельсинов
  23. List<Orange> oranges = new List<Orange> { new Orange(), new Orange(), new Orange() };
  24.  
  25. // по факту мы должны передать в метод ForEach объект делгата Action<Orange>,
  26. // который принимает апельсин и возвращает void, но благодаря контравариантности
  27. // можем передать Action<Fruit> т.е. записываем в переменную типа Action<Orange> объект типа Action<Fruit>
  28. // контравариантность переварачивает порядок наследования
  29. // Orange : Fruit => Action<Fruit> : Action<Orange>
  30. // Fruit fruit = new Orange();
  31. // Action<Orange> action = new Action<Fruit>(fruit => fruit.Eat());
  32. oranges.ForEach(actionWithFruit);
  33. }
  34. }
Compilation error #stdin compilation error #stdout 0.01s 33480KB
stdin
Standard input is empty
compilation info
prog.cs(32,17): error CS1502: The best overloaded method match for `System.Collections.Generic.List<Orange>.ForEach(System.Action<Orange>)' has some invalid arguments
/usr/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)
prog.cs(32,17): error CS1503: Argument `#1' cannot convert `System.Action<Fruit>' expression to type `System.Action<Orange>'
Compilation failed: 2 error(s), 0 warnings
stdout
Standard output is empty