gpt4 book ai didi

c# - 字符串和 Enumerable.Count

转载 作者:行者123 更新时间:2023-11-30 16:50:33 25 4
gpt4 key购买 nike

<分区>

Enumerable.Count 的文档中我们看到如果源实现了一个特殊情况 ICollection<T>

If the type of source implements ICollection, that implementation is used to obtain the count of elements. Otherwise, this method determines the count.

这在 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因为它是不可变的。

因此调用Enumerable.Countstring 上每次都会遍历整个字符串,即使它是不可变的。

所以我的问题是,为什么 ICollection 有一个特例?但不适用于 String .

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com