让FirstMethod
被定义为迭代器方法。假定SecondMethod
被定义为调用FirstMethod
,但直接返回结果而不是foreach
以及其项目。如果ThirdMethod
遍历SecondMethod
的结果,是整个链处理为迭代,还是实现这样的必须我yield
里面的SecondMethod
?返回迭代器方法
例如
IEnumerable<string> FirstMethod()
{
yield return "one";
yield return "two";
yield return "three";
}
IEnumerable<string> SecondMethod()
{
return FirstMethod();
}
IEnumerable<string> ThirdMethod()
{
foreach (string item in SecondMethod())
{
yield return item;
}
}
void Main()
{
foreach (string item in ThirdMethod())
{
Console.WriteLine(item);
}
}
我意识到我仍然会得到所有的项目在这个例子中显示。然而,我担心的是保留迭代器的“懒惰”评估直到Main
。
你可以在你的例子中加入一些'Console.WriteLine()'调用并自己回答。 –