考虑到 a 的边界List是已知的,是否.Last()枚举集合?
我问这个是因为文档说它是由Enumerable(在这种情况下它需要枚举集合)定义的
如果它确实枚举了集合,那么我可以简单地通过索引访问最后一个元素(正如我们所知道的.Counta List<T>)但是必须这样做似乎很愚蠢......
如果集合是一个IEnumerable<T>而不是一个IList<T>(使用数组或列表,将使用索引),它会枚举集合。
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();
}