按the documentation:
public class Queue<T> : IEnumerable<T>, ICollection, IEnumerable
所以它實現了通用IEnumerable<T>
接口,但非通用ICollection
接口。
不要讓名稱的相似性欺騙你 - ICollection
和ICollection<T>
是完全獨立的接口,而像這樣的東西(實現一些通用接口但只有非通用的其他接口)是不尋常的,這是完全合法的。
我懷疑是有它的設計者真的不想在Queue<T>
支持ICollection<T>
各個方面,但同樣地,他們希望實施ICollection
,讓人們從非通用類Queue
無痛升級。
編輯:正如丹尼斯的回答中指出的,ICollection.CopyTo
在Queue<T>
中明確實施。這意味着您可以通過ICollection
類型的表達式來獲得該簽名,即只有。例如:
Queue<string> queue = new Queue<string>();
Array array = new Button[10];
queue.CopyTo(array, 0, queue.Count); // Compilation failure...
ICollection collection = (ICollection) queue;
collection.CopyTo(array, 0, queue.Count); // Compiles, but will go bang
服用強類型數組將是有效的方法來實現ICollection<T>.CopyTo
,但ICollection<T>
的Add
和Remove
方法是不存在的 - 相反,你註定要Enqueue
和Dequeue
值。
的可能重複的[C#堆棧實現ICollection的,但是具有自ICollection方法](http://stackoverflow.com/questions/10589803/c-sharp-stack-implements-icollection-but-has-methods-from- icollectiont) –
nawfal