IList and List Conversions with Interfaces

后端 未结 6 1623
攒了一身酷
攒了一身酷 2021-01-03 01:06

I generally understand interfaces, inheritance and polymorphism, but one thing has me puzzled.

In this example, Cat implements IAnimal

6条回答
  •  旧时难觅i
    2021-01-03 01:48

    IList is not a covariant interface (or it would be IList). This is because IList both takes type T as a parameter and returns it as a return value from methods, which makes covariance problematic.

    For example, if in your example:

    IList cats = new List();

    You wanted to add a new cat, from cats, it would allow:

    cats.Add(new Dog());

    assuming Dog also implemented IAnimal, this is obviously incorrect and wouldn't work. Which is why IList is not a covariant or contravariant interface.

提交回复
热议问题