C# List源碼分析


C# List源碼分析

官網源碼地址

https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs

關鍵點

  • List實際容器為泛型數組
  • Count表示數組的已使用長度
  • Capacity表示數組長度
  • Capacity>=Count
  • List數組容量自動擴充實現方式
    • 當容量大小為0時 初始化一個大小為4的數組
    • 當容量大小非0時 初始化一個大小為原大小2倍的數組
    • 把原數組數據淺拷貝到新數組中
  • 設置Capacity容量大小實現方式(正常不使用)
  • 把原數組拷貝到新Capacity容量大小的數組中

優化點

  • 已知容器大小的情況 直接初始化對應大小的容器
  • 查找項索引的時候可以用BinarySearch查找

方法分析

public List();//初始化了一個大小為零的泛型數組
public List(IEnumerable<T> collection);//初始化了一個大小為collection.Count的泛型數組
public List(int capacity);//初始化了一個大小為capacity的泛型數組

public T this[int index] { get; set; }//獲取或設置指定索引的值 異常判斷索引是否正確

public int Count { get; }//獲取數組實際使用的數量
public int Capacity { get; set; }//獲取或設置原數組拷貝到新Capacity容量大小的數組中 異常判斷設置大小小於數組使用數量

public void Add(T item);//判斷是否自動擴容 賦值到數組中
public void AddRange(IEnumerable<T> collection);//調用InsertRange
public ReadOnlyCollection<T> AsReadOnly();//返回只讀數據
public int BinarySearch(T item);
public int BinarySearch(T item, IComparer<T> comparer);
public int BinarySearch(int index, int count, T item, IComparer<T> comparer);//二分查找查找匹配項
public void Clear();//清除數組Array.Clear
public bool Contains(T item);//判斷是否包含 算法復雜度O(n) 
public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter);//轉換為其他類型
public void CopyTo(int index, T[] array, int arrayIndex, int count);//拷貝到數組
public void CopyTo(T[] array, int arrayIndex);
public void CopyTo(T[] array);
public bool Exists(Predicate<T> match);//判斷是否存匹配函數 調用FindIndex
public T Find(Predicate<T> match);//查找匹配函數項 調用FindIndex
public List<T> FindAll(Predicate<T> match);//查找匹配函數項列表 算法復雜度O(n) 
public int FindIndex(Predicate<T> match);//
public int FindIndex(int startIndex, Predicate<T> match);
public int FindIndex(int startIndex, int count, Predicate<T> match);//從前查找匹配函數項索引
public T FindLast(Predicate<T> match);
public int FindLastIndex(Predicate<T> match);
public int FindLastIndex(int startIndex, Predicate<T> match);
public int FindLastIndex(int startIndex, int count, Predicate<T> match);//從后查找匹配函數項索引
public void ForEach(Action<T> action);//遍歷對每項執行action
public Enumerator GetEnumerator();//獲取遍歷枚舉數
public List<T> GetRange(int index, int count);//獲取范圍中的項
public int IndexOf(T item, int index, int count);//查找項索引 Array.IndexOf
public int IndexOf(T item, int index);
public int IndexOf(T item);
public void Insert(int index, T item);//插入指定索引項 如果自動擴容原數組拷貝到新容量大小的數組中
public void InsertRange(int index, IEnumerable<T> collection);//插入多個項到指定索引
public int LastIndexOf(T item);
public int LastIndexOf(T item, int index);
public int LastIndexOf(T item, int index, int count);//從后查找索引
public bool Remove(T item);//刪除項 實際調用IndexOf RemoveAt
public int RemoveAll(Predicate<T> match);//刪除所有匹配項
public void RemoveAt(int index);//刪除索引項 異常判斷索引是否正確
public void RemoveRange(int index, int count);//刪除范圍內項目 異常判斷參數是否正確
public void Reverse(int index, int count);//反轉順序 異常判斷參數是否正常
public void Reverse();//Reverse(0, Count);
public void Sort(Comparison<T> comparison);
public void Sort(int index, int count, IComparer<T> comparer);//指定范圍、函數排序
public void Sort();//Sort(0, Count, null);
public void Sort(IComparer<T> comparer);//Sort(0, Count, comparer);
public T[] ToArray();//轉換為數組 返回一個新數組
public void TrimExcess();//刪除多余容量 實際調用Capacity = Count;
public bool TrueForAll(Predicate<T> match);//判斷每項是否與函數都匹配

自定義List

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public interface IMyList<T> : ICollection<T>
{
    T this[int index] { get; set; }
    int IndexOf(T item);
    void Insert(int index, T item);
    void RemoveAt(int index);
}

public class MyList<T> : IEnumerable, ICollection, IList, ICollection<T>, IEnumerable<T>, IList<T>, IMyList<T>
{
    /// <summary>
    ///  空數組
    /// </summary>
    static readonly T[] _emptyArray = new T[0];
    /// <summary>
    ///  默認容量數量
    /// </summary>
    private const int _defaultCapacity = 4;


    /// <summary>
    /// 所有項
    /// </summary>
    private T[] _items;
    /// <summary>
    /// 實際使用容量大小
    /// </summary>
    private int _size;
    /// <summary>
    /// 版本
    /// </summary>
    private int _version;


    #region 公開方法

    /// <summary>
    /// 初始化 其實就是長度位0的數組
    /// </summary>
    public MyList()
    {
        _items = _emptyArray;
    }

    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="collection">收集對象</param>
    public MyList(IEnumerable<T> collection)
    {
        if (collection == null)
        {
            return;
        }

        ICollection<T> c = collection as ICollection<T>;
        if (c != null)
        {
            int count = c.Count;
            if (count == 0)
            {
                _items = _emptyArray;
            }
            else
            {
                _items = new T[count];
                c.CopyTo(_items, 0);
                _size = count;
            }
        }
        else
        {
            _size = 0;
            _items = _emptyArray;

            using (IEnumerator<T> en = collection.GetEnumerator())
            {
                while (en.MoveNext())
                {
                    Add(en.Current);
                }
            }
        }
    }

    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="capacity">容量大小</param>
    public MyList(int capacity)
    {
        if (capacity < 0)
        {
            //異常
            return;
        }
        else if (capacity == 0)
        {
            _items = _emptyArray;
        }
        else
        {
            _items = new T[capacity];
        }
    }

    /// <summary>
    /// 獲取或設置值
    /// </summary>
    /// <param name="index">索引</param>
    /// <returns></returns>
    public T this[int index]
    {
        get
        {
            if ((uint)index >= (uint)_size) { return default(T); }//異常

            return _items[index];
        }

        set
        {
            if ((uint)index >= (uint)_size) { return; }//異常

            _items[index] = value;
            _version++;
        }
    }

    /// <summary>
    /// 獲得或設置實際容量大小
    /// </summary>
    public int Capacity
    {
        get
        {
            return _items.Length;
        }
        set
        {
            if (value < _size)
            {
                //新容量小於實際容量 異常
                return;
            }

            if (value == _items.Length)
            {
                //新容量等於實際容量  不處理
                return;
            }


            if (value > 0)
            {
                //創建一個新大小的容量
                T[] newItems = new T[value];
                if (_size > 0)
                {
                    //原本數據淺拷貝到新容量去
                    Array.Copy(_items, 0, newItems, 0, _size);
                }
                _items = newItems;
            }
            else
            {
                _items = _emptyArray;
            }
        }
    }

    /// <summary>
    /// 獲得容量大小
    /// </summary>
    public int Count
    {
        get
        {
            return _size;
        }
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="item">項</param>
    public void Add(T item)
    {
        if (_size == _items.Length)
        {
            EnsureCapacity(_size + 1);
        }
        _items[_size++] = item;
        _version++;
    }

    /// <summary>
    /// 添加一列
    /// </summary>
    /// <param name="collection">收集對象</param>
    public void AddRange(IEnumerable<T> collection)
    {
        InsertRange(_size, collection);
    }

    /// <summary>
    /// 返回當前集合的只讀
    /// </summary>
    /// <returns></returns>
    public ReadOnlyCollection<T> AsreadOnly()
    {
        return new ReadOnlyCollection<T>(this);
    }

    /// <summary>
    /// 二分查找查找匹配項
    /// </summary>
    /// <param name="index">索引</param>
    /// <param name="count">匹配數量</param>
    /// <param name="item">匹配項</param>
    /// <param name="comparer">匹配方法</param>
    /// <returns></returns>
    public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
    {
        if (index < 0) { return -1; }//異常
        if (count < 0) { return -1; }//異常
        if (_size - index < count) { return -1; }//異常

        return Array.BinarySearch<T>(_items, index, count, item, comparer);
    }

    /// <summary>
    /// 二分查找查找匹配項
    /// </summary>
    /// <param name="item">匹配項</param>
    /// <returns></returns>
    public int BinarySearch(T item)
    {
        return BinarySearch(0, Count, item, null);
    }

    /// <summary>
    /// 二分查找查找匹配項
    /// </summary>
    /// <param name="item">匹配項</param>
    /// <param name="comparer">匹配方法</param>
    /// <returns></returns>
    public int BinarySearch(T item, IComparer<T> comparer)
    {
        return BinarySearch(0, Count, item, comparer);
    }

    /// <summary>
    /// 清除數據
    /// </summary>
    public void Clear()
    {
        if (_size > 0)
        {
            Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
            _size = 0;
        }
        _version++;
    }

    /// <summary>
    /// 判斷是否包含(算法復雜度O(n))
    /// </summary>
    /// <param name="item">項</param>
    /// <returns></returns>
    public bool Contains(T item)
    {
        if ((Object)item == null)
        {
            for (int i = 0; i < _size; i++)
                if ((Object)_items[i] == null)
                    return true;
            return false;
        }
        else
        {
            EqualityComparer<T> c = EqualityComparer<T>.Default;
            for (int i = 0; i < _size; i++)
            {
                if (c.Equals(_items[i], item)) return true;
            }
            return false;
        }
    }

    /// <summary>
    /// 轉換列表為其他類型
    /// </summary>
    /// <typeparam name="TOutput"></typeparam>
    /// <param name="converter"></param>
    /// <returns></returns>
    public MyList<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
    {
        if (converter == null) { return null; }//異常

        MyList<TOutput> list = new MyList<TOutput>(_size);
        for (int i = 0; i < _size; i++)
        {
            list._items[i] = converter(_items[i]);
        }
        list._size = _size;
        return list;
    }

    /// <summary>
    /// 拷貝到
    /// </summary>
    /// <param name="index">索引</param>
    /// <param name="array">拷貝數組容器</param>
    /// <param name="arrayIndex">拷貝數組開始容器</param>
    /// <param name="count">數量</param>
    public void CopyTo(int index, T[] array, int arrayIndex, int count)
    {
        if (_size - index < count) { return; }//異常

        Array.Copy(_items, index, array, arrayIndex, count);
    }

    /// <summary>
    /// 拷貝到
    /// </summary>
    /// <param name="array">拷貝數組容器</param>
    /// <param name="arrayIndex">拷貝數組開始容器</param>
    public void CopyTo(T[] array, int arrayIndex)
    {
        Array.Copy(_items, 0, array, arrayIndex, _size);
    }

    /// <summary>
    /// 拷貝到
    /// </summary>
    /// <param name="array">拷貝數組容器</param>
    public void CopyTo(T[] array)
    {
        CopyTo(array, 0);
    }

    /// <summary>
    /// 判斷是否存在
    /// </summary>
    /// <param name="match"></param>
    /// <returns></returns>
    public bool Exists(Predicate<T> match)
    {
        return FindIndex(match) != -1;
    }

    /// <summary>
    /// 從前查找匹配項索引
    /// </summary>
    /// <param name="match">匹配函數委托</param>
    /// <returns></returns>
    public int FindIndex(Predicate<T> match)
    {
        return FindIndex(0, _size, match);
    }

    /// <summary>
    /// 從前查找匹配項索引
    /// </summary>
    /// <param name="startIndex">查找開始索引</param>
    /// <param name="match">匹配函數委托</param>
    /// <returns></returns>
    public int FindIndex(int startIndex, Predicate<T> match)
    {
        return FindIndex(startIndex, _size - startIndex, match);
    }

    /// <summary>
    /// 從前查找匹配項索引
    /// </summary>
    /// <param name="startIndex">查找開始索引</param>
    /// <param name="count">查找數量</param>
    /// <param name="match">匹配函數委托</param>
    /// <returns></returns>
    public int FindIndex(int startIndex, int count, Predicate<T> match)
    {
        if ((uint)startIndex > (uint)_size) { return -1; }//異常

        if (count < 0 || startIndex > _size - count) { return -1; }//異常

        if (match == null) { return -1; }//異常

        int endIndex = startIndex + count;
        for (int i = startIndex; i < endIndex; i++)
        {
            if (match(_items[i])) return i;
        }
        return -1;
    }

    /// <summary>
    /// 從后查找匹配項索引
    /// </summary>
    /// <param name="match">匹配函數委托</param>
    /// <returns></returns>
    public T FindLast(Predicate<T> match)
    {
        if (match == null) { return default(T); }//異常

        for (int i = _size - 1; i >= 0; i--)
        {
            if (match(_items[i]))
            {
                return _items[i];
            }
        }
        return default(T);
    }

    /// <summary>
    /// 從后查找匹配項索引
    /// </summary>
    /// <param name="match">匹配函數委托</param>
    /// <returns></returns>
    public int FindLastIndex(Predicate<T> match)
    {
        return FindLastIndex(_size - 1, _size, match);
    }

    /// <summary>
    /// 從后查找匹配項索引
    /// </summary>
    /// <param name="startIndex">查找開始索引</param>
    /// <param name="match">匹配函數委托</param>
    /// <returns></returns>
    public int FindLastIndex(int startIndex, Predicate<T> match)
    {
        return FindLastIndex(startIndex, startIndex + 1, match);
    }

    /// <summary>
    /// 從后查找匹配項索引
    /// </summary>
    /// <param name="startIndex">查找開始位置</param>
    /// <param name="count">查找數量</param>
    /// <param name="match"></param>
    /// <returns></returns>
    public int FindLastIndex(int startIndex, int count, Predicate<T> match)
    {
        if (match == null) { return -1; }//異常

        if (_size == 0)
        {
            // 0長度列表的特殊情況
            if (startIndex != -1) { return -1; }//異常
        }
        else
        {
            // Make sure we're not out of range            
            if ((uint)startIndex >= (uint)_size) { return -1; }//異常 不在范圍之內
        }

        if (count < 0 || startIndex - count + 1 < 0) { return -1; }//異常 參數不對

        int endIndex = startIndex - count;
        for (int i = startIndex; i > endIndex; i--)
        {
            if (match(_items[i]))
            {
                return i;
            }
        }
        return -1;
    }

    /// <summary>
    /// 對每項執行函數
    /// </summary>
    /// <param name="action">執行函數</param>
    public void ForEach(Action<T> action)
    {
        if (action == null) { return; }//異常

        int version = _version;

        for (int i = 0; i < _size; i++)
        {
            //防止多線程操作
            if (version != _version)
            {
                break;
            }
            action(_items[i]);
        }
    }

    /// <summary>
    /// 獲得枚舉對象
    /// </summary>
    /// <returns></returns>
    public Enumerator GetEnumerator()
    {
        return new Enumerator(this);
    }

    /// <summary>
    /// 獲取范圍對象
    /// </summary>
    /// <param name="index"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    public MyList<T> GetRange(int index, int count)
    {
        if (index < 0) { return null; }//異常

        if (count < 0) { return null; }//異常

        if (_size - index < count) { return null; }//異常

        MyList<T> list = new MyList<T>(count);
        Array.Copy(_items, index, list._items, 0, count);
        list._size = count;
        return list;
    }

    /// <summary>
    /// 查找索引
    /// </summary>
    /// <param name="item">項</param>
    /// <returns></returns>
    public int IndexOf(T item)
    {
        return Array.IndexOf(_items, item, 0, _size);
    }

    /// <summary>
    /// 查找索引
    /// </summary>
    /// <param name="item">項</param>
    /// <param name="index">查找開始索引</param>
    /// <returns></returns>
    public int IndexOf(T item, int index)
    {
        if (index > _size) { return -1; }//異常

        return Array.IndexOf(_items, item, index, _size - index);
    }

    /// <summary>
    /// 查找索引
    /// </summary>
    /// <param name="item">項</param>
    /// <param name="index">查找開始索引</param>
    /// <param name="count">查找數量</param>
    /// <returns></returns>
    public int IndexOf(T item, int index, int count)
    {
        if (index > _size) { return -1; }//異常

        if (count < 0 || index > _size - count) { return -1; }//異常

        return Array.IndexOf(_items, item, index, count);
    }

    /// <summary>
    /// 插入一個數據
    /// </summary>
    /// <param name="index">索引</param>
    /// <param name="item">項</param>
    public void Insert(int index, T item)
    {
        // Note that insertions at the end are legal.
        if ((uint)index > (uint)_size)
        {
            return;//索引超出 異常
        }
        if (_size == _items.Length)
        {
            EnsureCapacity(_size + 1);//插入到最后需要擴容一下
        }
        if (index < _size)
        {
            Array.Copy(_items, index, _items, index + 1, _size - index);//把索引后面的數據向后挪一個位置
        }
        _items[index] = item;//替換指定索引位置的項
        _size++;
        _version++;
    }

    /// <summary>
    /// 插入一列數據
    /// </summary>
    /// <param name="index">索引</param>
    /// <param name="collection">收集對象</param>
    public void InsertRange(int index, IEnumerable<T> collection)
    {
        if (collection == null)
        {
            return;//異常
        }

        if ((uint)index > (uint)_size)
        {
            return;//插入位置錯誤 異常
        }

        ICollection<T> c = collection as ICollection<T>;
        if (c != null)
        {    // if collection is ICollection<T>
            int count = c.Count;
            if (count > 0)
            {
                //擴容
                EnsureCapacity(_size + count);
                if (index < _size)
                {
                    //容量夠 直接拷貝進來
                    Array.Copy(_items, index, _items, index + count, _size - index);
                }

                //如果插入的列表是自己
                if (this == c)
                {
                    //分2步插入
                    Array.Copy(_items, 0, _items, index, index);
                    Array.Copy(_items, index + count, _items, index * 2, _size - index);
                }
                else
                {
                    T[] itemsToInsert = new T[count];
                    c.CopyTo(itemsToInsert, 0);
                    itemsToInsert.CopyTo(_items, index);
                }
                _size += count;
            }
        }
        else
        {
            using (IEnumerator<T> en = collection.GetEnumerator())
            {
                while (en.MoveNext())
                {
                    Insert(index++, en.Current);
                }
            }
        }
        _version++;
    }

    /// <summary>
    /// 從后查找索引
    /// </summary>
    /// <param name="item">項</param>
    /// <returns></returns>
    public int LastIndexOf(T item)
    {
        if (_size == 0)
        {  // Special case for empty list
            return -1;
        }
        else
        {
            return LastIndexOf(item, _size - 1, _size);
        }
    }

    /// <summary>
    /// 從后查找索引
    /// </summary>
    /// <param name="item">項</param>
    /// <param name="index">開始索引</param>
    /// <returns></returns>
    public int LastIndexOf(T item, int index)
    {
        if (index >= _size) { return -1; }//異常

        return LastIndexOf(item, index, index + 1);
    }

    /// <summary>
    /// 從后查找索引
    /// </summary>
    /// <param name="item">項</param>
    /// <param name="index">開始索引</param>
    /// <param name="count">數量</param>
    /// <returns></returns>
    public int LastIndexOf(T item, int index, int count)
    {
        if ((Count != 0) && (index < 0)) { return -1; }//異常

        if ((Count != 0) && (count < 0)) { return -1; }//異常

        if (_size == 0) { return -1; }//空列表的特殊情況

        if (index >= _size) { return -1; }//異常

        if (count > index + 1) { return -1; }//異常


        return Array.LastIndexOf(_items, item, index, count);
    }

    /// <summary>
    /// 刪除項
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public bool Remove(T item)
    {
        int index = IndexOf(item);
        if (index >= 0)
        {
            RemoveAt(index);
            return true;
        }

        return false;
    }

    /// <summary>
    /// 刪除索引項
    /// </summary>
    /// <param name="index"></param>
    public void RemoveAt(int index)
    {
        if ((uint)index >= (uint)_size) { return; }//異常

        _size--;

        if (index < _size)
        {
            Array.Copy(_items, index + 1, _items, index, _size - index);
        }
        _items[_size] = default(T);
        _version++;
    }

    /// <summary>
    /// 刪除所有匹配項
    /// </summary>
    /// <param name="match"></param>
    /// <returns></returns>
    public int RemoveAll(Predicate<T> match)
    {
        if (match == null) { return -1; }//異常

        int freeIndex = 0;   // the first free slot in items array

        // 找到第一個需要刪除的項目。
        while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;

        //沒有匹配項
        if (freeIndex >= _size) return 0;

        int current = freeIndex + 1;
        while (current < _size)
        {
            // Find the first item which needs to be kept.
            while (current < _size && match(_items[current])) current++;

            if (current < _size)
            {
                // 將項復制到空閑槽。
                _items[freeIndex++] = _items[current++];
            }
        }

        Array.Clear(_items, freeIndex, _size - freeIndex);
        int result = _size - freeIndex;
        _size = freeIndex;
        _version++;
        return result;
    }

    /// <summary>
    /// 刪除范圍項
    /// </summary>
    /// <param name="index"></param>
    /// <param name="count"></param>
    public void RemoveRange(int index, int count)
    {
        if (index < 0) { return; }//異常

        if (count < 0) { return; }//異常

        if (_size - index < count) { return; }//異常

        if (count > 0)
        {
            int i = _size;
            _size -= count;
            if (index < _size)
            {
                Array.Copy(_items, index + count, _items, index, _size - index);
            }
            Array.Clear(_items, _size, count);
            _version++;
        }
    }

    /// <summary>
    /// 反轉排序
    /// </summary>
    public void Reverse()
    {
        Reverse(0, Count);
    }

    /// <summary>
    /// 反轉范圍排序
    /// </summary>
    /// <param name="index"></param>
    /// <param name="count"></param>
    public void Reverse(int index, int count)
    {
        if (index < 0) { return; }//異常

        if (count < 0) { return; }//異常

        if (_size - index < count) { return; }//異常

        Array.Reverse(_items, index, count);
        _version++;
    }

    /// <summary>
    /// 排序
    /// </summary>
    public void Sort()
    {
        Sort(0, Count, null);
    }

    /// <summary>
    /// 排序
    /// </summary>
    /// <param name="comparer">指定方法</param>
    public void Sort(IComparer<T> comparer)
    {
        Sort(0, Count, comparer);
    }

    /// <summary>
    /// 排序
    /// </summary>
    /// <param name="index">排序開始索引</param>
    /// <param name="count">排序數量</param>
    /// <param name="comparer">指定方法</param>
    public void Sort(int index, int count, IComparer<T> comparer)
    {
        if (index < 0) { return; }//異常

        if (count < 0) { return; }//異常

        if (_size - index < count) { return; }//異常

        Array.Sort<T>(_items, index, count, comparer);
        _version++;
    }

    /// <summary>
    /// 排序
    /// </summary>
    /// <param name="comparison">指定方法</param>
    public void Sort(Comparison<T> comparison)
    {
        if (comparison == null) { return; }//異常

        if (_size > 0)
        {
            IComparer<T> comparer = new FunctorComparer<T>(comparison);
            Array.Sort(_items, 0, _size, comparer);
        }
    }

    /// <summary>
    /// 轉換為數組
    /// </summary>
    /// <returns></returns>
    public T[] ToArray()
    {
        T[] array = new T[_size];
        Array.Copy(_items, 0, array, 0, _size);
        return array;
    }

    /// <summary>
    /// //將容器設置位實際數目
    /// </summary>
    public void TrimExcess()
    {
        int threshold = (int)(((double)_items.Length) * 0.9);
        if (_size < threshold)
        {
            Capacity = _size;
        }
    }

    /// <summary>
    /// 判斷每個項目都匹配
    /// </summary>
    /// <param name="match"></param>
    /// <returns></returns>
    public bool TrueForAll(Predicate<T> match)
    {
        if (match == null) { return false; }//異常

        for (int i = 0; i < _size; i++)
        {
            if (!match(_items[i]))
            {
                return false;
            }
        }
        return true;
    }

    #endregion

    #region 私有方法

    /// <summary>
    /// 保護容量
    /// </summary>
    /// <param name="min">最小容量</param>
    private void EnsureCapacity(int min)
    {
        if (_items.Length < min)
        {
            int newCapacity;

            if (_items.Length == 0)
            {
                //如果本身長度為0則 新容量為4
                newCapacity = _defaultCapacity;
            }
            else
            {
                //新容量為原長度2被
                newCapacity = _items.Length * 2;
            }

            //不能超過int最大值
            if ((uint)newCapacity > int.MaxValue)
            {
                newCapacity = int.MaxValue;
            }
            //新容量不能小於參數
            if (newCapacity < min)
            {
                newCapacity = min;
            }
            Capacity = newCapacity;
        }
    }

    #endregion

    #region 接口實現

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new Enumerator(this);
    }

    bool ICollection.IsSynchronized
    {
        get { return false; }
    }

    private Object _syncRoot;
    object ICollection.SyncRoot
    {
        get
        {
            if (_syncRoot == null)
            {
                System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
            }
            return _syncRoot;
        }
    }

    void ICollection.CopyTo(Array array, int arrayIndex)
    {
        if ((array != null) && (array.Rank != 1)) { return; }//異常

        try
        {
            Array.Copy(_items, 0, array, arrayIndex, _size);
        }
        catch (ArrayTypeMismatchException) { return; }//異常
    }

    object IList.this[int index]
    {
        get { return this[index]; }
        set
        {
            try
            {
                this[index] = (T)value;
            }
            catch (InvalidCastException) { return; }//異常
        }
    }

    bool IList.IsFixedSize
    {
        get { return false; }
    }

    bool IList.IsReadOnly
    {
        get { return false; }
    }

    int IList.Add(Object item)
    {
        try
        {
            Add((T)item);
        }
        catch (InvalidCastException) { return -1; }//異常

        return Count - 1;
    }

    bool IList.Contains(Object item)
    {
        if (IsCompatibleObject(item))
        {
            return Contains((T)item);
        }
        return false;
    }

    int IList.IndexOf(Object item)
    {
        if (IsCompatibleObject(item))
        {
            return IndexOf((T)item);
        }
        return -1;
    }

    void IList.Insert(int index, object item)
    {
        Insert(index, (T)item);
    }

    void IList.Remove(object value)
    {
        if (IsCompatibleObject(value))
        {
            Remove((T)value);
        }
    }

    bool ICollection<T>.IsReadOnly
    {
        get { return false; }
    }

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return GetEnumerator();
    }

    private static bool IsCompatibleObject(object value)
    {
        return ((value is T) || (value == null && default(T) == null));
    }

    #endregion


    /// <summary>
    /// Comparison實現IComparer接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal sealed class FunctorComparer<T> : IComparer<T>
    {
        Comparison<T> comparison;

        public FunctorComparer(Comparison<T> comparison)
        {
            this.comparison = comparison;
        }

        public int Compare(T x, T y)
        {
            return comparison(x, y);
        }
    }

    [Serializable]
    public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
    {
        private MyList<T> list;
        private int index;
        private int version;
        private T current;

        internal Enumerator(MyList<T> list)
        {
            this.list = list;
            index = 0;
            version = list._version;
            current = default(T);
        }

        public void Dispose()
        {
        }

        public bool MoveNext()
        {

            MyList<T> localList = list;

            if (version == localList._version && ((uint)index < (uint)localList._size))
            {
                current = localList._items[index];
                index++;
                return true;
            }
            return MoveNextRare();
        }

        private bool MoveNextRare()
        {
            if (version != list._version) { return false; }//異常

            index = list._size + 1;
            current = default(T);
            return false;
        }

        public T Current
        {
            get
            {
                return current;
            }
        }

        Object System.Collections.IEnumerator.Current
        {
            get
            {
                if (index == 0 || index == list._size + 1) { return false; }//異常

                return Current;
            }
        }

        void System.Collections.IEnumerator.Reset()
        {
            if (version != list._version) { return; }//異常

            index = 0;
            current = default(T);
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。