如果集合是 IEnumerable<T>
而不是 IList<T>
(使用 Array 或 List 会使用索引),则它将枚举集合。
Enumerable.Last
的实现方式如下(使用ILSpy):
public static TSource Last<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
IList<TSource> list = source as IList<TSource>;
if (list != null)
{
int count = list.Count;
if (count > 0)
{
return list[count - 1];
}
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
TSource current;
do
{
current = enumerator.Current;
}
while (enumerator.MoveNext());
return current;
}
}
}
throw Error.NoElements();
}
List<T>
的枚举...但是你的第一行说“是”;-) - MatthewIList<T>
,那么它将遍历整个枚举。”虽然有点令人困惑,但是是正确的。 - dlevList<T>
明显实现了 IList<T>
,所以... 我的标题不应该是“否”吗?我知道这只是纯粹的语义问题... 只是想知道你的回答中是否有什么我没注意到的东西... - Matthew
List<T>
,那么不要依赖于可能未经记录的优化程序,在快速方式下访问最后一个元素。(恰好Last()
会检查接收器是否实现了IList<T>
并对这种情况进行了优化。) - dlev.Last
实现的问题 - MatthewList<T>
并尽可能通过索引访问最后一个元素。 - Lee