IList and List Conversions with Interfaces

后端 未结 6 1636
攒了一身酷
攒了一身酷 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条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 01:36

    C# doesn't support this kind of variance on IList for type-safety reasons.

    If C# did support this, what would you expect to happen here?

    IList cats = new List();
    
    cats.Add(new Dog());         // a dog is an IAnimal too
    cats.Add(new Squirrel());    // and so is a squirrel
    

    In C#4 you're able to do something like this:

    IEnumerable cats = new List();
    

    This is because the IEnumerable interface does support variance of this kind. An IEnumerable is a read-only sequence, so there's no way that you could subsequently add a Dog or a Squirrel to an IEnumerable that's actually a list of Cat.

提交回复
热议问题