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

前端 未结 3 1584
长情又很酷
长情又很酷 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:49

    I believe this depends on which version of .Net you're using. I could be mistaken, but in .Net 4 I think you can do

    animalList.AddRange(dogList);
    

    Otherwise in .Net 3.5, you can do

    animalList.AddRange(dogList.Select(x => (Animal)x));
    

提交回复
热议问题