Мне нужна коллекция Covariant, элементы которой могут быть восстановлены по индексу. IEnumerable - единственная коллекция .net, которую я знаю, это Covariant, но она не поддерживает эту индексацию.
В частности, я хотел бы сделать это:
List<Dog> dogs = new List<Dog>();
IEnumerable<Animal> animals = dogs;
IList<Animal> animalList = dogs; // This line does not compile
Теперь я знаю, почему это проблема. Список реализует ICollection
, у которого есть метод Add. При добавлении к IList
животных, это позволило бы последующему коду добавлять любого типа животных, которые не допускаются в "настоящую" коллекцию List<Dog>
.
Знает ли кто-нибудь о коллекции, которая поддерживает индексные запросы, которые также являются ковариантными? Я бы не хотел создавать свои собственные.