i covariant collection items can retrieved index. ienumerable .net collection i'm aware of covariant, not have index support.
specifically, i'd this:
list<dog> dogs = new list<dog>(); ienumerable<animal> animals = dogs; ilist<animal> animallist = dogs; // line not compile
now, i'm aware of why problem. list implements icollection
has add method. casting ilist
of animals, allow subsequent code add type of animal not allowed in "real" list<dog>
collection.
so aware of collection supports index lookups covariant? not create own.
update: .net 4.5 onwards there ireadonlylist<out t>
, ireadonlycollection<out t>
both covariant; latter ienumerable<out t>
plus count
; former adds t this[int index] {get;}
. should noted ienumerable<out t>
covariant .net 4.0 onwards.
both list<t>
, readonlycollection<t>
(via list<t>.asreadonly()
) implement both of these.
it can covariant if has get
indexer, i.e.
public t this[int index] { get; }
but main collections have {get;set;}
, makes awkward. i'm not aware of suffice there, wrap it, i.e. write extension method:
var covariant = list.ascovariant();
which wrapper around ilist<t>
exposes ienumerable<t>
, get
indexer...? should few minutes work...
public static class covariance { public static iindexedenumerable<t> ascovariant<t>(this ilist<t> tail) { return new covariantlist<t>(tail); } private class covariantlist<t> : iindexedenumerable<t> { private readonly ilist<t> tail; public covariantlist(ilist<t> tail) { this.tail = tail; } public t this[int index] { { return tail[index]; } } public ienumerator<t> getenumerator() { return tail.getenumerator();} ienumerator ienumerable.getenumerator() { return tail.getenumerator(); } public int count { { return tail.count; } } } } public interface iindexedenumerable<out t> : ienumerable<t> { t this[int index] { get; } int count { get; } }
Comments
Post a Comment