Why generic IList<> does not inherit non-generic IList

前端 未结 4 1713
谎友^
谎友^ 2020-12-03 05:44

IList does not inherit IList where IEnumerable inherits IEnumerable.

If out mo

4条回答
  •  甜味超标
    2020-12-03 06:18

    As you note, T in IList is not covariant. As a rule of thumb: any class that can modify its state cannot be covariant. The reason is that such classes often have methods that have T as the type of one of their parameters, e.g. void Add(T element). And covariant type parameters are not allowed in input positions.

    Generics were added, among other reasons, to provide type safety. For example, you can't add an Elephant to a list of Apple. If ICollection were to extend ICollection, then you could call ((ICollection)myApples).Add(someElephant) without a compile-time error, as ICollection has a method void Add(object obj), which seemingly allows you to add any object to the list, while in practice you can only add objects of T. Therefore, ICollection does not extend ICollection and IList does not extend IList.

    Anders Hejlsberg, one of the creators of C#, explains it like this:

    Ideally all of the generic collection interfaces (e.g. ICollection, IList) would inherit from their non-generic counterparts such that generic interface instances could be used both with generic and non-generic code.

    As it turns out, the only generic interface for which this is possible is IEnumerable, because only IEnumerable is contra-variant [sic1]: In IEnumerable, the type parameter T is used only in "output" positions (return values) and not in "input" positions (parameters). ICollection and IList use T in both input and output positions, and those interfaces are therefore invariant.

    1) IEnumerable is co-variant


    Since .Net 4.5 there are the IReadOnlyCollection and IReadOnlyList covariant interfaces. But IList, ICollection and many of the list and collection classes don't implement or extend them. Frankly, I find them not very useful, as they only define Count and this[int index].


    If I could redesign .Net 4.5 from the ground up, I would have split the list interface into a read-only covariant interface IList that includes Contains and IndexOf, and a mutable invariant interface IMutableList. Then you could cast IList to IList. I implemented this here:

    M42 Collections - Covariant collections, lists and arrays.

    提交回复
    热议问题