System.Array 不支持 Add(),那么集合初始化器是如何工作的呢?

System.Array does not support Add(), so how does collection initializer work?

在 C# 中,您可以像这样初始化数组:

var example = new int[] { 1, 4, 3 };

引述于Custom Collection Initializers

The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer.

但是您不能添加到 System.Array,必须为每个添加的项目创建一个新的更大的数组,这对性能不利。那么在数组上使用集合初始值设定项时,C# 是如何工作的呢?我想知道我是否可以编写一个 class 和一个支持集合初始值设定项的内部数组。

您提供的报价与自定义 collection 相关。

但是数组不是自定义的 collection,它是内置类型并且有自己的可用初始化语法规范 here。特别是,该规范不需要任何 Add 方法。

Array 不是自定义集合。它是一个数组。 array 初始化器 pre-date 集合初始化器,是 syntax.

的灵​​感来源