Mar*_*cel 4 c# arrays icollection
看看这段疯狂的代码:
ICollection<int> list = new[] {1, 2, 3};
list.Add(4); // NotSupportedException: Collection was of a fixed size.
Run Code Online (Sandbox Code Playgroud)
我不怀疑这个例外!我想知道可以将一个简单的数组分配给ICollection<T>. 我看到了Array工具IList,ICollection但据我所知它从未实现ICollection<T>!
我看到 Array 实现了 IList 和 ICollection 但据我所知它从未实现 ICollection
它确实实现了ICollection<T>,实现只是在运行时注入。
从文档:
从.NET Framework 2.0开始,Array类实现
System.Collections.Generic.IList<T>,System.Collections.Generic.ICollection<T>以及System.Collections.Generic.IEnumerable<T>通用接口。实现在运行时提供给数组,因此,泛型接口不会出现在 Array 类的声明语法中。此外,没有关于只能通过将数组转换为通用接口类型(显式接口实现)来访问的接口成员的参考主题。将数组转换为这些接口之一时要注意的关键是添加、插入或删除元素的成员抛出 NotSupportedException。