.NET中提供了一種稱為集合的類型,類似於數組,將一組類型化對象組合在一起,可通過遍歷獲取其中的每一個元素
本篇記錄一個自定義集合的小實例。自定義集合需要通過實現System.Collections命名空間提供的集合接口實現,常用接口有:
ICollection:定義所有非泛型集合的大小,枚舉數和同步方法
IComparer:公開一種比較兩個對象的方法
IDictionary:表示鍵/值對的非通用集合
IDictionaryEnumerator:枚舉非泛型字典的元素
IEnumerable:公開枚舉數,該枚舉數支持在非泛型集合上進行簡單的迭代
IEnumerator:支持對非泛型集合的簡單迭代
IList:表示可按照索引單獨訪問的對象非泛型集合
今天的這個實例,以繼承IEnumerable為例,繼承該接口時需要實現該接口的方法,IEnumerable GetEnumerator()
在實現該IEnumerable的同時,需要實現 IEnumerator接口,該接口有3個成員,分別是:
Current屬性,MoveNext方法和Reset方法,其定義如下:
Object Current{get;}
bool MoveNext();
void Reset();
案例實現如下:
1.定義一個商品類:作為集合類中的元素類
public class Goods { public string Code; public string Name; public Goods(string code,string name) { this.Code = code; this.Name = name; } }
2.定義集合類,繼承IEnumerable和IEnumerator接口
public class JHClass:IEnumerable,IEnumerator//定義集合類 { private Goods[] _goods; //初始化Goods類型集合 public JHClass(Goods[]gArray) { _goods = new Goods[gArray.Length]; for (int i=0;i<gArray.Length;i++) { _goods[i] = gArray[i]; } } /// <summary> /// 實現IEnumerable接口中的GetEnumerator方法 /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)this; } int position = -1; //記錄索引位置 // 實現IEnumerator接口中的Current方法 object IEnumerator.Current { get { return _goods[position]; } } public bool MoveNext() { position++; return (position < _goods.Length); } public void Reset() { position = -1; } }
3.功能實現,實現自定義集合的遍歷,輸出元素信息
static void Main(string[] args) { Goods[] goodsArray = new Goods[3] { new Goods("T0001","小米電視機"), new Goods("T0002","華為榮耀4X"), new Goods("T0003","聯想服務器"), }; JHClass jhList = new JHClass(goodsArray); foreach (Goods g in jhList) //遍歷集合 { Console.WriteLine(g.Code + " " + g.Name); } Console.ReadLine(); }
執行后輸出: