簡體   English   中英

了解列表中的枚舉器<t></t>

[英]Understanding Enumerator in List<T>

枚舉器的源代碼是:

public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator {
   private List<T> list;
   private int index;
   private int version;
   private T current;
   ...
   public bool MoveNext() {

      List<T> localList = list;  <--------------Q1

      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) {
         ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
      }

      index = list._size + 1;   <-----------------Q2
      current = default(T);
      return false;
   }
   
void System.Collections.IEnumerator.Reset() {
      if (version != list._version) {
         ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
      }

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

我對這個迭代器模式有一些疑問:

Q1-為什么MoveNext方法需要定義一個localList ,既然List<T>已經是引用類型,為什么不能直接使用私有字段list ,為什么需要為其創建別名?

Q2- 當索引超出列表中最后一個元素的范圍時, MoveNextRare方法將調用,那么增加它的意義何在,為什么不保持不變,因為當Reset()調用時,索引無論如何都會設置為 0 ?

對於第一個問題,我沒有任何答案,也許它只是以前實現的遺物,也許它以某種方式提高了性能(盡管我想知道如何以及為什么,所以我的賭注是第一個猜測)。 同樣在 Core implementation list字段中被標記為readonly

至於第二個 - 它與Reset無關,但與System.Collections.IEnumerator.Current 實現無關:

Object System.Collections.IEnumerator.Current {
    get {
        if( index == 0 || index == list._size + 1) { // check second comparasion
            ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
    }
    return Current;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM