標籤:
ICollection 介面是 System.Collections 命名空間中類的基底介面,ICollection 介面擴充 IEnumerable,IDictionary 和 IList 則是擴充 ICollection 的更為專用的介面。如果 IDictionary 介面和 IList 介面都不能滿足所需集合的要求,則從 ICollection 介面派生新集合類以提高靈活性。
ICollection是IEnumerable的加強型介面,它繼承自IEnumerable介面,提供了同步處理、賦值及返回內含元素數目的功能
一、ICollection介面的原型
C# 代碼 複製
namespace System.Collections{ // 摘要: // 定義所有非泛型集合的大小、列舉程式和同步方法。 [ComVisible(true)] public interface ICollection : IEnumerable { // 摘要: // 擷取 System.Collections.ICollection 中包含的元素數。 // // 返回結果: // System.Collections.ICollection 中包含的元素數。 int Count { get; } // // 摘要: // 擷取一個值,該值指示是否同步對 System.Collections.ICollection 的訪問(安全執行緒)。 // // 返回結果: // 如果對 System.Collections.ICollection 的訪問是同步的(安全執行緒),則為 true;否則為 false。 bool IsSynchronized { get; } // // 摘要: // 擷取一個可用於同步對 System.Collections.ICollection 的訪問的對象。 // // 返回結果: // 可用於同步對 System.Collections.ICollection 的訪問的對象。 object SyncRoot { get; } // 摘要: // 從特定的 System.Array 索引處開始,將 System.Collections.ICollection 的元素複製到一個 System.Array // 中。 // // 參數: // array: // 作為從 System.Collections.ICollection 複製的元素的目標位置的一維 System.Array。System.Array // 必須具有從零開始的索引。 // // index: // array 中從零開始的索引,將在此處開始複製。 // // 異常: // System.ArgumentNullException: // array 為 null。 // // System.ArgumentOutOfRangeException: // index 小於零。 // // System.ArgumentException: // array 是多維的。- 或 -源 System.Collections.ICollection 中的元素數目大於從 index 到目標 array // 末尾之間的可用空間。 // // System.ArgumentException: // 源 System.Collections.ICollection 的類型無法自動轉換為目標 array 的類型。 void CopyTo(Array array, int index); }}
二、IEnumerable介面
1、IEnumerable介面是ICollection的父介面,凡實現此介面的類,都具備“可迭代”的能力。
2、IEnumerable介面只定義了一個方法:GetEnumerator,該方法將返回一個“迭代子”對象(或稱為迭代器對象),是一個實現了IEnumerator介面的對象執行個體。
3、凡是實現了IEnumerable介面的類,都可以使用foreach迴圈迭代遍曆。
三、簡單的ICollection實現範例
C# 代碼 複製
public class MyCollectioin:ICollection{ private string[] list; private object root; public MyCollection() { list = new string[3]{"1","3","4"}; } #region ICollection Members public bool IsSynchronized { get{ return true; } } public int Count { get { return list.Length; } } public void CopyTo(Array array,int index) { list.CopyTo(array,index); } public object SyncRoot { get { return root; } } #endregioin #region IEnumerable Members public IEnumerable GetEnumerator() { return list.GetEnumerator(); } #endregion}
四、ICollection<T>
ICollection<T>是可以統計集合中對象的標準介面。該介面可以確定集合的大小(Count),集合是否包含某個元素(Contains),複製集合到另外一個數組(ToArray),集合是否是唯讀(IsReadOnly)。如果一個集合是可編輯的,那麼可以調用Add,Remove和Clear方法操作集合中的元素。因為該介面繼承IEnumerable<T>,所以可以使用foreach語句遍曆集合。
ICollection<T>定義源碼
C# 代碼 複製
public interface ICollection<T> : IEnumerable<T>{ // Number of items in the collections. int Count { get; } bool IsReadOnly { get; } void Add(T item); void Clear(); bool Contains(T item); // CopyTo copies a collection into an Array, starting at a particular // index into the array. // void CopyTo(T[] array, int arrayIndex); //void CopyTo(int sourceIndex, T[] destinationArray, int destinationIndex, int count); bool Remove(T item);}
C#中ICollection介紹