我不明白当前可以为null,最后一个可以是一个对象,而最后一个是LINQ函数.我以为最后使用GetEnumerator并一直持续到current == null并返回该对象.但是你可以看到第一个GetEnumerator().当前为null,最后以某种方式返回一个对象.
linq Last()如何工作?
var.GetEnumerator().Current
var.Last()
Run Code Online (Sandbox Code Playgroud)
Chr*_*ich 19
使用反射的System.Core.dll:
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();
}
Run Code Online (Sandbox Code Playgroud)
Last()将调用GetEnumerator(),然后继续调用MoveNext()/ Current直到MoveNext()返回false,此时它返回Current检索的最后一个值.通常,Nullity不用作序列中的终止符.
所以实现可能是这样的:
public static T Last<T>(this IEnumerable<T> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
using (IEnumerator<T> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
throw new InvalidOperationException("Empty sequence");
}
T value = iterator.Current;
while (iterator.MoveNext())
{
value = iterator.Current;
}
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
(这可以通过foreach循环实现,但上面更明确地显示了交互.这也忽略了直接访问最后一个元素的可能性.)