你能解释一下'yield'关键字在Enumerable方面是如何工作的吗?例如。我不明白下面程序的代码如何返回 IEnumerable 类型的对象:
class Program
{
static IEnumerable<T> Merge<T>(IEnumerable<T> left, IEnumerable<T> right)
where T: IComparable<T>
{
IEnumerator<T> l = left.GetEnumerator();
IEnumerator<T> r = right.GetEnumerator();
bool l_has_data = l.MoveNext();
bool r_has_data = r.MoveNext();
while (l_has_data || r_has_data)
{
if (!l_has_data && r_has_data)
{
yield return r.Current;
r_has_data = r.MoveNext();
continue;
}
if (!r_has_data && l_has_data)
{
yield return l.Current;
l_has_data = l.MoveNext();
continue;
}
int comp = l.Current.CompareTo(r.Current);
if (comp < 0)
{
yield return l.Current;
l_has_data = l.MoveNext();
}
else if (comp > 0)
{
yield return r.Current;
r_has_data = r.MoveNext();
}
else
{
yield return l.Current;
yield return r.Current;
l_has_data = l.MoveNext();
r_has_data = r.MoveNext();
}
}
}
如果我将鼠标悬停在“.Current”上,它会告诉我这“获取枚举器当前位置的元素”。