Comparison of common delegates C#



  •   using System;
    
    // Контрвариантность обобщений.
    // Контрвариантность обобщений в C# 4.0 ограничена делегатами.
    
    namespace Generics
    {
    class Animal { }
    class Cat : Animal { }
    
    class Program
    {
        delegate void MyDelegate<in T>(T a);  // in - Для аргумента.
    
        public static void CatUser(Animal animal)
        {
            Console.WriteLine(animal.GetType().Name);
        }
    
        static void Main()
        {
    
            MyDelegate<Animal> delegateAnimal = new MyDelegate<Animal>(CatUser);
            //MyDelegate<Cat> delegateCat = delegateAnimal;     
    
            MyDelegate<Cat> delegateCat=new MyDelegate<Animal>(CatUser);
            delegateAnimal(new Animal());
            delegateCat(new Cat());
    
            delegateAnimal(new Cat());
            //    delegateCat(new Animal()); // Невозможно.
    
            // Delay.
            Console.ReadKey();
        }
      }
    }
    

    why not cause delegateCat(new Animal()); Thank you.



  • Because the type of announcement is important, not the puncture.

    MyDelegate<Cat> delegateCat=new MyDelegate<Animal>(CatUser);
    

    Such an award is possible because any function that takes an animal animal may accept a cat as it.

    ♪ I need a cat trainer.
    - Animal master's gonna be okay?
    - Yeah.

    why not? delegateCat(new Animal());?

    Because the compiler sees the function of the cat. Potentially such a function may cause cattle missing from an animal. The compiler doesn't know if he's doing this, he just trusts a software player who says that it's a cat that doesn't need any animal.

    ♪ We have a great cat trainer.
    ♪ Can he address an unknown animal?
    ♪ We don't know, so the beast doesn't fit. Come with the cat.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2