2016-01-22 98 views
3

在爲Enumerable.Count的文檔,我們看到一種特殊情況的處理,如果源實現ICollection<T>字符串和Enumerable.Count

如果源類型實現ICollection的,即實現用於獲取元素的個數。否則,此方法確定計數。

,這是在其implementation可見:

public static int Count<TSource>(this IEnumerable<TSource> source) { 
    if (source == null) throw Error.ArgumentNull("source"); 
    ICollection<TSource> collectionoft = source as ICollection<TSource>; 
    if (collectionoft != null) return collectionoft.Count; 
    ICollection collection = source as ICollection; 
    if (collection != null) return collection.Count; 
    int count = 0; 
    using (IEnumerator<TSource> e = source.GetEnumerator()) { 
     checked { 
      while (e.MoveNext()) count++; 
     } 
    } 
    return count; 
} 

現在,讓我們看看string。該String類具有以下特徵:

public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable, IComparable<string>, IEnumerable<char>, IEquatable<string> 

我們可以在這裏看到,它並沒有實現ICollection,因爲它是不可變的。

因此,在string上調用Enumerable.Count將在每次迭代整個字符串,即使它是不可變的。

所以我的問題是,爲什麼有一個ICollection的特殊情況,但不是String

+1

你多長時間一次使用「IEnumerable 」的「未知」實現工作與使用你知道的東西的次數相比,具體而言,它是一個'字符串',因此可以簡單地訪問'Length'在上面? –

+0

'ICollection'是一個由所有集合類型實現的接口,因此對這些類型進行優化是合乎邏輯的。但考慮單一類型的專門化方法是沒有意義的。如果你對字符串進行了這種優化,那麼會出現另一個問題,爲什麼不對所有具有「長度」屬性的類型進行此操作? –

+0

@selsman22如? –

回答

2

這隻會得到基於意見的答案,但我懷疑人們不會經常在字符串上使用.Count()

此外,您支持的每種附加類型都會特別減慢計數,而不需要特定的實現。

所以儘管執行過程中完全有可能考慮字符串,但我懷疑設計師選擇它並不值得。