C#泛型集合類型實現(xiàn)添加和遍歷
在"C#中List<T>是怎么存放元素的"中,分析了List<T>的源碼,了解了List<T>是如何存放元素的。這次,就自定義一個泛型集合類型,可實現(xiàn)添加元素,并支持遍歷
該泛型集合類型一定需要一個添加元素的方法,在添加元素的時候需要考慮:當添加的元素超過當前數(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
- 添加方法考慮了當count計數(shù)等于當前元素的長度,就讓數(shù)組擴容為當前的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)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
詳解如何通過wireshark實現(xiàn)捕獲C#上傳的圖片
這篇文章主要為大家詳細介紹了如何通過wireshark實現(xiàn)捕獲C#上傳的圖片,文中的示例代碼簡潔易懂,具有一定的學習價值,感興趣的小伙伴可以了解下2023-11-11
使用 BenchmarkDotNet 對 C# 代碼進行基準測試
這篇文章主要介紹了使用 BenchmarkDotNet 對 C# 代碼進行基準測試,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下2021-03-03
C#使用MailAddress類發(fā)送html格式郵件的實例代碼
這篇文章主要介紹如何使用C#的MailAddress類發(fā)送郵件的方法,大家參考使用吧2013-11-11
C#調(diào)用Windows的API實現(xiàn)窗體動畫
在VF、VB、PB的應(yīng)用中,有些無法通過語言工具本身來完成的或者做得不理想的功能,我們會考慮通過Windows的API來完成。本文就來通過調(diào)用Windows的API實現(xiàn)窗體動畫,感興趣的可以嘗試一下2022-11-11

