Cannot convert from List to List

后端 未结 3 1904
我在风中等你
我在风中等你 2021-02-01 13:33

I have a set up like this:

abstract class Foo {}
class Bar : Foo {}

and a method elsewhere of this form:

void AddEntries(List&l         


        
3条回答
  •  故里飘歌
    2021-02-01 14:07

    Have a read of Covariance and Contravariance in Generics from docs.microsoft.com as this, particularly the section "Generic Interfaces with Covariant Type Parameters" will cover off the scenario that you're working with.

    In short, if you (can) change the signature of your AddEntries method to:

    static void AddEntries(IEnumerable entries)
    

    (Note the use of IEnumerable instead of List) you'll be able to do what you're looking to do.

    The specific difference here is that the IEnumerable and List are declared differently:

    public interface IEnumerable : IEnumerable
    public class List : IList, ... ...
    

    The difference that matters is the out in the declaration of IEnumerable which indicates that it is covariant which means (with the definition taken from docs.microsoft.com):

    Covariance: Enables you to use a more derived type than originally specified.

提交回复
热议问题