c# - 为什么 System.Array 类实现 IList 但不提供 Add()

标签 c# list system.array

这段代码:

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 成员有用 - 例如IsFixedSizeIsReadOnlyIndexOf()...只是一个想法。

最佳答案

为什么 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 的原因。

供引用:Why array implements IList?

关于c# - 为什么 System.Array 类实现 IList 但不提供 Add(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38117870/

相关文章:

c# - 如何制作一个整数数组的列表?

.net - 将 System.Array 从 .Net 编码到 vb6

c# - 在 Dynamics CRM C# 插件中检索查找字段的显示值

c# - GAC 中的 .Net 静态变量和 DLL 版本

c# - 方法是否使用? : Operator Inlined during JIT compilation?

c# - System.Array.IndexOf 分配内存

C# 遍历枚举? (索引 System.Array)

c# - 从 CRM 加载数据的性能问题

Python:如何从字典列表中创建一个 csv 字符串(无文件)?

java - 创建实例时指定集合元素类型