为什么以这种方式实现DefaultIfEmpty? [英] Why is DefaultIfEmpty implemented this way?
问题描述
追逐System.Linq.Enumerable.DefaultIfEmpty
的实现将我带到了这种方法.除了以下古朴的细节,它看起来还不错:
Chasing the implementation of System.Linq.Enumerable.DefaultIfEmpty
took me to this method. It looks alright except for the following quaint details:
// System.Linq.Enumerable
[IteratorStateMachine(typeof(Enumerable.<DefaultIfEmptyIterator>d__90<>))]
private static IEnumerable<TSource> DefaultIfEmptyIterator<TSource>(IEnumerable<TSource> source, TSource defaultValue)
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
do
{
yield return enumerator.Current;
}
while (enumerator.MoveNext());
}
else
{
yield return defaultValue;
}
}
IEnumerator<TSource> enumerator = null;
yield break;
yield break;
}
1)为什么一旦确定序列不为空,则为什么代码必须遍历整个序列?
1) Why does the code have to iterate over the whole sequence once it has been established that the sequence is not empty?
2)为什么收益率最终会下降两次?
2) Why the yield break two times at the end?
3)为什么在没有其他引用的情况下,将enumerator
显式设置为null?
3) Why explicitly set the enumerator
to null at the end when there is no other reference to it?
我会留在这里:
// System.Linq.Enumerable
[IteratorStateMachine(typeof(Enumerable.<DefaultIfEmptyIterator>d__90<>))]
private static IEnumerable<TSource> DefaultIfEmptyIterator<TSource>(IEnumerable<TSource> source, TSource defaultValue)
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
do
{
yield return enumerator.Current;
}
// while (enumerator.MoveNext());
}
else
{
yield return defaultValue;
}
}
// IEnumerator<TSource> enumerator = null;
yield break;
// yield break;
}
推荐答案
DefaultIfEmpty
需要充当以下角色:
-
如果可枚举的源没有条目,则它需要充当具有单个值的枚举;默认值.
If the source enumerable has no entries, it needs to act as an enumerable with a single value; the default value.
如果可枚举的源不为空,则需要充当可枚举的源.因此,它需要产生所有值.
If the source enumerable is not empty, it needs to act as the source enumerable. Therefore, it needs to yield all values.
这篇关于为什么以这种方式实现DefaultIfEmpty?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!