固定大小到列表

use*_*546 25 c# collections

对于声明透视,允许以下内容

    IList<string> list= new string[3];
    list.Add("Apple");
    list.Add("Manago");
    list.Add("Grapes");
Run Code Online (Sandbox Code Playgroud)

1)它编译很好,但运行时我收到"Collection was of fixed size"错误.当然,集合是按大小动态增长的,为什么这样的声明被编译器接受?

2)我可以分配给IList的不同列表是什么?例

IList<string> fruits=new List<string>();
Run Code Online (Sandbox Code Playgroud)

在这里,我将List分配给IList,我可以分配给IList的各种集合类有哪些?

Jar*_*Par 42

这里的根本问题是System.Array通过实施违反替代原则IList<T>.甲System.Array类型具有不能改变的固定大小.Add方法IList<T>用于向底层集合添加一个新元素,并将其大小增加1.这对于a是不可能的System.Array,因此它会抛出.

什么System.Array真的要在这里实现是一个只读的风格IList<T>.不幸的是,框架中不存在这样的类型,因此它实现了下一个最好的事情:IList<T>.

关于什么类型可分配的问题IList<T>,实际上有很多包括:ReadOnlyCollection<T>Collection<T>.这个清单太长了,无法放在这里.看到这一切的最好方法是IList<T>在反射器中打开并查找派生类型IList<T>.


Jak*_*son 6

当您调用list.Add时,您试图将项目插入到数组的末尾.数组是固定大小的集合,因此您无法执行添加.相反,您必须通过索引器分配条目:

list[0] = "a";
list[1] = "b";
list[2] = "c";
Run Code Online (Sandbox Code Playgroud)