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

后端 未结 4 2016
后悔当初
后悔当初 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:31

    Look at this:

    List ships = new List();
    List asChiefs = (List)ships;
    asChiefs.Add(new Car());
    // so what, now ships[0] is a Car?
    

    That's why you cannot treat a list of ships as a list of chiefs. If you want to learn more about this, it is said that List is not covariant (and neither is it contravariant).

    Now, does your AssignRandomProperties method really need to take a List? If all you do is iterate it, you don't need a List, you can do fine with an IEnumerable, which List implements. The good thing here is IEnumerable provides no methods for modification of the list, so it is covariant (starting with .NET 4). This means you can do this:

    IEnumerable chiefs = ships;
    

提交回复
热议问题