日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#泛型集合類型實現添加和遍歷_C#教程

作者:Darren?Ji ? 更新時間: 2022-10-23 編程語言

在"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
            {
                get { return Current; }
            }
            public bool MoveNext()
            {
                return ++index < _myList.count;
            }
            public void Reset()
            {
                index = -1;
            }
        }
    }
  • 泛型集合類型維護著一個T類型的泛型數組
  • 私有字段count是用來計數的,每添加一個元素計數加1
  • 添加方法考慮了當count計數等于當前元素的長度,就讓數組擴容為當前的2倍
  • 迭代器實現了IEnumerator<T>接口

客戶端調用。

    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的區別是什么呢?
其實,真正執行迭代的是IEnumerator迭代器。IEnumerable接口就提供了一個方法,就是返回IEnumerator迭代器。

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

原文鏈接:https://www.cnblogs.com/darrenji/p/3978354.html

欄目分類
最近更新