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

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

    You can use Cast ()

    //You must have using System.Linq;
    
    List dogs = new List ();
    List animals = new List ();
    animals.AddRange (dogs.Cast ());
    

    EDIT : As dlev points out, if you run framework 4 you don't need to cast.

提交回复
热议问题