在"C#中List<T>是怎么存放元素的"中,分析了List<T>的源碼,了解了List<T>是如何存放元素的。這次,就自定義一個泛型集合類型,可實現添加元素,并支持遍歷。
該泛型集合類型一定需要一個添加元素的方法,在添加元素的時候需要考慮:當添加的元素超過當前數組的容量,就讓數組擴容;為了支持循環遍歷,該泛型集合類型必須提供一個迭代器(實現IEnumerator接口)。
public class MyList<T>{T[] items = new T[5];PRivate int count;public void Add(T item){if(count == items.Length)Array.Resize(ref items, items.Length * 2);items[count++] = item;}public IEnumerator<T> GetEnumerator(){return new MyEnumeraor(this);}class MyEnumeraor : IEnumerator<T>{private int index = -1;private MyList<T> _myList;public MyEnumeraor(MyList<T> myList){_myList = myList;}public T Current{get{if (index < 0 || index >= _myList.count){return default(T);}return _myList.items[index];}}public void Dispose(){}object System.Collections.IEnumerator.Current{
新聞熱點
疑難解答