C#自定義集合類(一)
阿新 • • 發佈:2020-05-01
.NET中提供了一種稱為集合的型別,類似於陣列,將一組型別化物件組合在一起,可通過遍歷獲取其中的每一個元素
自定義集合需要通過實現System.Collections名稱空間提供的集合介面實現,常用介面有:
- ICollection:定義所有非泛型集合的大小,列舉數和同步方法
- IComparer:公開一種比較兩個物件的方法
- IDictionary:表示鍵/值對的非通用集合
- IDictionaryEnumerator:列舉非泛型字典的元素
- IEnumerable:公開列舉數,該列舉數支援在非泛型集合上進行簡單的迭代
- IEnumerator:支援對非泛型集合的簡單迭代
- IList:表示可按照索引單獨訪問的物件非泛型集合
以繼承IEnumerable為例,繼承該介面時需要實現該介面的方法,IEnumerableGetEnumerator()
在實現該IEnumerable的同時,需要實現 IEnumerator介面,該介面有3個成員,分別是:
Object Current{get;}
bool MoveNext();
void Reset();
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Collections;View Codenamespace ConsoleApplication1 { public class Goods { public String Code { get; set; } public String Name { get; set; } public Goods(String code,String name) { this.Code = code; this.Name = name; } } public class JHClass : IEnumerable,IEnumerator {private Goods[] _goods; public JHClass(Goods[] gArray) { this._goods = new Goods[gArray.Length]; for (int i = 0; i < gArray.Length; i++) { this._goods[i] = gArray[i]; } } //實現IEnumerable介面中的GetEnumerator方法 IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)this; } int position = -1; object IEnumerator.Current { get { return _goods[position]; } } public bool MoveNext() { position++; return (position < _goods.Length); } public void Reset() { position = -1; } } class Program { static void Main() { Goods[] goodsArray = { new Goods("1001","戴爾筆記本"),new Goods("1002","華為筆記本"),new Goods("1003","華碩筆記本") }; JHClass jhList = new JHClass(goodsArray); foreach (Goods g in jhList) Console.WriteLine(g.Code + " " + g.Name); Console.ReadLine(); } } }