共用方式為


使用 Visual C# 實作自訂集合

本逐步文章說明如何在Visual C# 中實作自定義集合。 Microsoft .NET Framework 基類庫提供集合 System.Collections.ICollection 介面的正式定義。

原始產品版本: Visual C#
原始 KB 編號: 307484

在自定義類別中實作 ICollection 介面

ICollection 介面繼承自 IEnumerable 介面。 介面 ICollection 會定義方法和三個 CopyTo 唯讀屬性: IsSynchronizedSyncRootCountICollectionGetEnumerator繼承 介面中的 IEnumerable 方法。 自訂集合類別應該實作 ICollection 介面。

若要實作 ICollection 介面,請遵循下列步驟:

  1. 在 Visual C# .NET 中,建立 Windows 應用程式。

  2. 在 方案總管 中,以滑鼠右鍵按兩下專案名稱,指向 [新增],然後按兩下 [新增類別] 以新增名為 CustomCollection 的類別模組。

  3. 將下列範例程式代碼新增至類別模組的開頭,以匯入 System.Collection 命名空間:

    using System.Collections;
    
  4. 使用下列範例程式代碼取代模組中的任何其他程式代碼:

    public class CustomCollection : ICollection
    {
        private int[] intArr = {1,5,9};
        private int Ct;
    
        public CustomCollection()
        {
            Ct=3;
        }
    }
    

    為了簡單起見,類別 CustomCollection 會保存具有三個整數專案和 count 變數的陣列。

  5. 實作 CopyTo 方法,此方法會採用整數數位和索引做為參數。 這個方法會從傳遞的索引開始,將集合中的專案複製到陣列。 若要實作此方法,請在公用 CustomCollection 建構函式後面貼上下列程序代碼:

    void ICollection.CopyTo(Array myArr, int index)
    {
        foreach (int i in intArr)
        {
            myArr.SetValue(i,index);
            index = index+1;
        }
    }
    
  6. 實作 GetEnumerator 方法,這個方法是由 ICollection 介面繼承自 IEnumerable。 方法 GetEnumerator 會傳回可逐一 Enumerator 查看集合的物件。 在 方法後面 CopyTo 貼上下列範例程式代碼:

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new Enumerator(intArr);
    }
    
  7. 若要實作三個唯讀屬性,請在 方法後面 GetEnumerator 貼上下列程序代碼:

    // The IsSynchronized Boolean property returns True if the
    // collection is designed to be thread safe; otherwise, it returns False.
    bool ICollection.IsSynchronized
    {
        get
        {
            return false;
        }
    }
    
    // The SyncRoot property returns an object, which is used for synchronizing
    // the collection. This returns the instance of the object or returns the
    // SyncRoot of other collections if the collection contains other collections.
    object ICollection.SyncRoot
    {
        get
        {
            return this;
        }
    }
    
    // The Count read-only property returns the number
    // of items in the collection.
    int ICollection.Count
    {
        get
        {
            return Ct;
        }
    }
    

實作 GetEnumerator 方法的 Enumerator 物件

本節說明如何建立可逐一 Enumerator 查看 CustomCollection的類別。

  1. 將下列範例程式代碼貼到類別模組中的 end class 語句之後:

    public class Enumerator : IEnumerator
    {
        private int[] intArr;
        private int Cursor;
    }
    

    宣告私用intArr整數陣列,以在呼叫 方法時GetEnumerator保存 類別的專案CustomCollection。 欄位 Cursor 成員在列舉時會保留目前的位置。

  2. 將 建構函式新增 intArr 為 參數,並將本機 intArr 設定為這個 。 在成員欄位的宣告之後貼上下列範例程式代碼:

    public Enumerator(int[] intarr)
    {
        this.intArr = intarr;
        Cursor = -1;
    }
    
  3. 實作 ResetMoveNext 方法。 若要這樣做,請在建構函式後面貼上下列程序代碼:

    void IEnumerator.Reset()
    {
        Cursor = -1;
    }
    bool IEnumerator.MoveNext()
    {
        if (Cursor < intArr.Length)
            Cursor++;
    
        return(!(Cursor == intArr.Length));
    }
    

    Reset 會將 Cursor 設定為 -1 ,並將 MoveNext 移至 Cursor 下一個專案。 MoveNext 如果成功,會傳 回 True

  4. 實作 Current 只讀屬性,這個屬性會傳回 所 Cursor指向的專案。 Cursor如果 為 -1,則會產生 InvalidOperationException。 在 方法後面 MoveNext 貼上下列程式代碼:

    object IEnumerator.Current
    {
        get
        {
            if((Cursor < 0) || (Cursor == intArr.Length))
                throw new InvalidOperationException();
            return intArr[Cursor];
        }
    }
    

針對每個 使用逐一查看自定義集合

  1. [Form1.cs] 的 [ 設計 ] 索引卷標上,將按鈕拖曳至窗體。

  2. 按兩下按鈕,並將下列範例程式代碼新增至 Click 按鈕的事件:

    CustomCollection MyCol = new CustomCollection();
    
    foreach (object MyObj in MyCol)
        MessageBox.Show(MyObj.ToString());
    
  3. 按 F5 以執行應用程式,然後按下按鈕。

    注意

    消息框會顯示自訂集合中的專案。

這是如何運作的? 針對每個呼叫 GetEnumerator 方法以建立 物件, Enumerator 並呼叫 MoveNext 方法,將 設定 Cursor 為第一個專案。 接著會存取目前的 屬性,以取得 中的 MyObj專案。 這會重複,直到 MoveNext回 False 為止。