C#泛型集合類型實現(xiàn)添加和遍歷
在"C#中List<T>是怎么存放元素的"中,分析了List<T>的源碼,了解了List<T>是如何存放元素的。這次,就自定義一個泛型集合類型,可實現(xiàn)添加元素,并支持遍歷
該泛型集合類型一定需要一個添加元素的方法,在添加元素的時候需要考慮:當(dāng)添加的元素超過當(dāng)前數(shù)組的容量,就讓數(shù)組擴容;為了支持循環(huán)遍歷,該泛型集合類型必須提供一個迭代器(實現(xiàn)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 { get { return Current; } } public bool MoveNext() { return ++index < _myList.count; } public void Reset() { index = -1; } } }
- 泛型集合類型維護著一個T類型的泛型數(shù)組
- 私有字段count是用來計數(shù)的,每添加一個元素計數(shù)加1
- 添加方法考慮了當(dāng)count計數(shù)等于當(dāng)前元素的長度,就讓數(shù)組擴容為當(dāng)前的2倍
- 迭代器實現(xiàn)了IEnumerator<T>接口
客戶端調(diào)用。
class Program { static void Main(string[] args) { MyList<int> list = new MyList<int>(); list.Add(1); list.Add(2); foreach (int item in list) { Console.WriteLine(item); } Console.ReadKey(); } }
另外,IEnumerable和IEnumerator的區(qū)別是什么呢?
其實,真正執(zhí)行迭代的是IEnumerator迭代器。IEnumerable接口就提供了一個方法,就是返回IEnumerator迭代器。
public interface IEnumerable { IEnumerator GetEnumerator(); }
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
C#基礎(chǔ):Dispose()、Close()、Finalize()的區(qū)別詳解
本篇文章是對c#中的Dispose()、Close()、Finalize()的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05基于WPF實現(xiàn)帶明細(xì)的環(huán)形圖表
這篇文章主要介紹了如何利用WPF繪制帶明細(xì)的環(huán)形圖表?,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定幫助,需要的可以參考一下2022-08-08C#取得Web程序和非Web程序的根目錄的N種取法總結(jié)
C#取得Web程序和非Web程序的根目錄的N種取法,方便大家知道,有更好的方法,請說明2008-03-03Unity的AssetPostprocessor?Model動畫函數(shù)使用案例深究
這篇文章主要介紹了Unity的AssetPostprocessor?Model動畫函數(shù)使用案例的深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08