Covariance vs. contravariance with respect to class inheritance

后端 未结 4 2342
猫巷女王i
猫巷女王i 2021-02-09 14:00

What is the meaning of the concepts \'covariance\' and \'contravariance\'?

Given 2 classes, Animal and Elephant (which inherits from

4条回答
  •  长发绾君心
    2021-02-09 14:37

    You should try reading pages 45-49 of Introducing .NET 4.0 With Visual Studio 2010 which deals with this exact example. It even has some nice photos of elephants.

    The main point to take out is, to do this

    var things = new List> { new ConcreteThing() }
    

    with:

    public class ConcreteThing : IThing
    {
    
    }
    

    you need the "out" in the interface definition, which will allow more specific forms to be set, but anything read out of IThing must be guaranteed to be the more general type.

    public interface IThing where T : IContent
    {
    }
    

提交回复
热议问题