Array 没有实现 ICollection<T> 但可以赋值
Array doesn't implement ICollection<T> but is assignable
看看这段疯狂的代码:
ICollection<int> list = new[] {1, 2, 3};
list.Add(4); // NotSupportedException: Collection was of a fixed size.
我不是在想异常!我想知道可以将一个简单的数组分配给 ICollection<T>
。我看到 Array
实现了 IList
和 ICollection
但据我所知它从未实现 ICollection<T>
!
I see Array implements IList and ICollection but as far as I know it
never implements ICollection
它确实实现了 ICollection<T>
,实现只是在 运行 时注入。
Starting with the .NET Framework 2.0, the Array class implements the
System.Collections.Generic.IList<T>
,
System.Collections.Generic.ICollection<T>
, and
System.Collections.Generic.IEnumerable<T>
generic interfaces. The
implementations are provided to arrays at run time, and as a result,
the generic interfaces do not appear in the declaration syntax for the
Array class. In addition, there are no reference topics for interface
members that are accessible only by casting an array to the generic
interface type (explicit interface implementations). The key thing to
be aware of when you cast an array to one of these interfaces is that
members which add, insert, or remove elements throw
NotSupportedException.
看看这段疯狂的代码:
ICollection<int> list = new[] {1, 2, 3};
list.Add(4); // NotSupportedException: Collection was of a fixed size.
我不是在想异常!我想知道可以将一个简单的数组分配给 ICollection<T>
。我看到 Array
实现了 IList
和 ICollection
但据我所知它从未实现 ICollection<T>
!
I see Array implements IList and ICollection but as far as I know it never implements ICollection
它确实实现了 ICollection<T>
,实现只是在 运行 时注入。
Starting with the .NET Framework 2.0, the Array class implements the
System.Collections.Generic.IList<T>
,System.Collections.Generic.ICollection<T>
, andSystem.Collections.Generic.IEnumerable<T>
generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class. In addition, there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.