我不明白 Current 如何可以为 null 而 LINQ 函数 Last() 可以返回一个对象。我认为 Last 使用 GetEnumerator 并一直持续到 current == null 并返回对象。然而,正如您所看到的,第一个 GetEnumerator().Current 为 null,最后一个以某种方式返回一个对象。
linq Last() 如何工作?
items.GetEnumerator().Current
items.Last()
从使用反射器 http://www.red-gate.com/products/reflector/ on 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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)