.NET基礎之集合

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   使用   sp   for   

集合可以說是數組的超集,集合可以維護對象數組,集合包含了更進階的功能。例如控制對其包含的對象的訪問、搜尋和排序等。數組是固定的,一旦我們建立好了數組,不能在現有數組的末尾添加新項,除非我們建立新的數組。

C#中的數組實現為System.Array類的執行個體,它們只是集合類中的一種,集合類的功能重要通過實現System.Collection名稱空間中的介面而獲得的。

 

System.Collection名稱空間中的幾個介面提供了基本的功能集合:

  • IEnumerable可以迭代集合中的項。這個介面中的唯一方法GetEnumerator()可以迭代集合中的各項。使用foreach結構的對象必須要實現這個方法
  • ICollection(繼承與IEnumerable)可以擷取集合中項的個數,並能把項複製到一個簡單的數群組類型中。ICollection中有CopyTo(System.Array array,int index)方法和Count屬性
  • IList(繼承於IEnumberable和ICollection)提供了集合的項列表,並可以訪問這些項,以及其他一些與項列表有關的功能。
  • IDictionary(繼承於IEnumerable和ICollection)類似於IList,但提供了通過鍵碼值而不是索引訪問的項列表。         

System.Array類實現了IList,ICollection,IEnumerable,但不支援IList的一些進階功能。

 

如何自訂集合類

    Collection類有介面IEnumerable,ICollection和IList,可以使用其提供的List和InnerList兩個受保護的屬性,它們可以訪問儲存的對象本身。

有一個Animal類:

Public class Animal{    //類成員}

      實現它的集合:

Public class Animals : CollectionBase{    public void Add(Animal newAnimal)    {        List.Add(newAnimal);    }    public void Remove(Animal oldAnimal)    {        List.Remove(oldAnimal);    }    public Animals()    {    }}

如果要通過索引訪問,就要添加索引符。添加索引符如下:

public class Animals : CollectionBase{    ...    public Animal this[int animalIndex]    {        get        {            return (Animal)List[animalIndex];        }        set        {            List[animalIndex] = value;        }    }}

自訂Dictionary,使可以通過關鍵字訪問

和上一個集合的實現例子非常類似,但是還是有一定的差別。要實現IDictionary介面,所以我們可以繼承DictionaryBase,具體細節如下:

public class Animals : DictionaryBase{    public void Add(string newID, Animal newAnimal)    {        Dictionary.Add(newID, newAnimal);    }        public void Remove(string oldID)    {        Dictionary.Remove(oldID);    }        public Animals() {}    public Animal this[string animalID]    {        get        {            return (Animal)Dictionary[animalID];        }        set        {            Dictionary[animalID] = value;        }    }}

.NET基礎之集合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.