How to pass a List to a method with parameter List?

后端 未结 4 1982
后悔当初
后悔当初 2021-01-05 23:53

I\'ve been away from inheritance for a while and need a little helping hand.

I have an abstract base class Chief. There are two inheriting classes

4条回答
  •  孤街浪徒
    2021-01-06 00:24

    First some explanation. You cannot convert List to List because then the Add method would have the signature void List.Add(Chief item) and you would be able to store instances of the Chief class in a list that was declared to only hold Vehicles. This would break the type system; therefore it is not allowed.

    The easiest way to get around this is to pass in theVehicles.ToList(). However, this will create a new list. This has two implications: (1) You would be wasting memory by duplicating the list, and (2) if the method is going to mutate the list itself (add/remove items or replace members with other members) you will not see those changes on the theVehicles list. (If the objects the references in the list point to are the only things being modified, this is not a problem.)

    If you have control over the AssignRandomProperties method, consider using this signature instead:

    public static void AssignRandomProperties(
        PSetList routeSettings,
        IList theChiefs) where T : Chief
    {
        ...
    }
    

提交回复
热议问题