Difference between Covariance & Contra-variance

前端 未结 5 1570
小鲜肉
小鲜肉 2020-11-22 10:20

I am having trouble understanding the difference between covariance and contravariance.

5条回答
  •  梦谈多话
    2020-11-22 10:52

    The converter delegate helps me to understand the difference.

    delegate TOutput Converter(TInput input);
    

    TOutput represents covariance where a method returns a more specific type.

    TInput represents contravariance where a method is passed a less specific type.

    public class Dog { public string Name { get; set; } }
    public class Poodle : Dog { public void DoBackflip(){ System.Console.WriteLine("2nd smartest breed - woof!"); } }
    
    public static Poodle ConvertDogToPoodle(Dog dog)
    {
        return new Poodle() { Name = dog.Name };
    }
    
    List dogs = new List() { new Dog { Name = "Truffles" }, new Dog { Name = "Fuzzball" } };
    List poodles = dogs.ConvertAll(new Converter(ConvertDogToPoodle));
    poodles[0].DoBackflip();
    

提交回复
热议问题