编程语言
首页 > 编程语言> > c#-数组未实现ICollection但可分配

c#-数组未实现ICollection但可分配

作者:互联网

这个问题已经在这里有了答案:            >            What interfaces do all arrays implement in C#?                                    5个
看看这段疯狂的代码:

ICollection<int> list = new[] {1, 2, 3};
list.Add(4); // NotSupportedException: Collection was of a fixed size.

我不奇怪这个例外!我想知道是否可以将一个简单的数组分配给ICollection< T>.我看到Array实现了IList和ICollection,但据我所知,它从未实现ICollection< T&gt ;!

解决方法:

I see Array implements IList and ICollection but as far as I know it
never implements ICollection

它确实实现了ICollection< T&gt ;,该实现只是在运行时注入的. 从documentation开始:

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,arrays,c
来源: https://codeday.me/bug/20191119/2032603.html