![](/img/trans.png)
[英]How to tell if an IEnumerable<T> is subject to deferred execution?
[英]About deferred execution of IEnumerable
在下面的代码中,我理解第二个初始化打印一个“外部”和三个“内部”。 但是为什么第一个根本不打印,我希望它可以打印一个“外部”。
DeferExecution a = new DeferExecution(); // prints nothing
DeferExecution b = new DeferExecution(null); // print one "outside" and three "inside".
class DeferExecution
{
public IEnumerable<string> Input;
public DeferExecution()
{
Input = GetIEnumerable();
}
public DeferExecution(string intput)
{
Input = GetIEnumerable().ToArray();
}
public IEnumerable<string> GetIEnumerable()
{
Console.WriteLine("outside");
var strings = new string[] {"a", "b", "c"};
foreach (var s in strings)
{
Console.WriteLine("inside");
yield return s;
}
}
}
返回的可枚举实现为迭代器块 (即,使用yield
的方法)。
直到第一次枚举迭代器块中的代码之后,它们才真正执行,因此,如果您实际上不使用IEnumerable
进行任何操作,您将看不到任何事情发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.