在Enumerable.Count的文档中,我们看到如果源实现了ICollection<T>,就会处理特殊情况。
如果源的类型实现ICollection,则该实现用于获取元素的计数。否则,此方法将确定计数。
这在其实现中是可见的:
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,因为它是不可变的。
因此,每次在一个Enumerable.Count上调用string都会迭代整个字符串,即使它是不可变的。
所以我的问题是,为什么ICollection有特例,而String却没有。
发布于 2016-01-22 10:07:27
这只会得到基于意见的答案,但我怀疑人们不会经常在字符串上使用.Count()。
此外,您支持的每一个附加类型都会在没有特定实现的情况下特别减缓类型的计数。
因此,虽然实现完全有可能考虑到字符串,但我怀疑设计者选择它是不值得的。
https://stackoverflow.com/questions/34943907
复制相似问题