Cannot convert from List to List

前端 未结 6 1382
庸人自扰
庸人自扰 2020-11-22 10:39

I\'m trying to pass A list of DerivedClass to a function that takes a list of BaseClass, but I get the error:

cannot convert from 
         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 11:07

    When you have a class derived from a base class, any containers of those classes are not automatically derived. So you cannot just cast a List to a List.

    Use .Cast() to create a new list where each object is cast back to the base class:

    List list1 = new List();
    List list2 = list1.Cast().ToList();
    

    Note that this is a new list, not a cast version of your original list, so operations on this new list will not reflect on the original list. Operations on the contained objects will reflect, however.

提交回复
热议问题