Covariance and contravariance real world example

后端 未结 9 1990
醉梦人生
醉梦人生 2020-11-22 16:57

I\'m having a little trouble understanding how I would use covariance and contravariance in the real world.

So far, the only examples I\'ve seen have been the same o

9条回答
  •  孤城傲影
    2020-11-22 17:47

    The converter delegate helps me to visualise both concepts working together:

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

提交回复
热议问题