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