这段代码:
int[] myArr = { 1, 2 };
myArr.Add(3);
在构建时抛出以下错误:
error CS1061: 'System.Array' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
IList
接口(interface)有Add()
方法,为什么Array没有实现?
更新:我从答案中看到它确实明确地实现了它,好的,我明白了,谢谢,我最好坚持这个问题:
为什么 Array
实际上没有提供 Add()
,或者,更好的是,为什么它必须实现 IList
首先?它可以是另一个接口(interface)(例如 IArray
)而不是实现 IList
,它可能只对 IList
的 Array 成员有用 - 例如IsFixedSize
、IsReadOnly
、IndexOf()
...只是一个想法。
最佳答案
为什么 Array 实际上不提供 Add()?
数组具有固定大小,因此您不能添加新元素。
The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance. https://msdn.microsoft.com/en-us/library/9b9dty7d.aspx
为什么首先要实现 IList?
Definition of IList: Represents a non-generic collection of objects that can be individually accessed by index.
https://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx
Array 通过索引访问,IList 容纳这个索引,这就是 Array 实现 IList 的原因。
关于c# - 为什么 System.Array 类实现 IList 但不提供 Add(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38117870/