C# - How to convert List to List, when Dog is a subclass of Animal?

前端 未结 3 1542
长情又很酷
长情又很酷 2021-01-17 14:17

I have a class Animal, and its subclass Dog. I have a List and I want to add the contents of some List<

3条回答
  •  被撕碎了的回忆
    2021-01-17 14:56

    You don't need the cast if you're using C#4:

    List animals = new List();
    List dogs = new List();
    
    animals.AddRange(dogs);
    

    That's allowed, because AddRange() accepts an IEnumerable, which is covariant.

    If you don't have C#4, though, then you would have to iterate the List and cast each item, since covariance was only added then. You can accomplish this via the .Cast extension method:

    animals.AddRange(dogs.Cast());
    

    If you don't even have C#3.5, then you'll have to do the casting manually.

提交回复
热议问题