我想要一个Covariant集合,其项目可以通过索引检索.IEnumerable是我所知道的唯一.net集合,它是Covariant,但它没有这个索引支持.
具体来说,我想这样做:
List<Dog> dogs = new List<Dog>();
IEnumerable<Animal> animals = dogs;
IList<Animal> animalList = dogs; // This line does not compile
Run Code Online (Sandbox Code Playgroud)
现在,我知道为什么这是一个问题.List实现ICollection具有Add方法.通过向上投射IList动物,它将允许后续代码添加"真实" List<Dog>集合中不允许的任何类型的动物.
那么有人知道一个支持索引查找的集合也是协变的吗?我想不创造自己的.