关于IEnumerable的延迟执行

hon*_*pei 1 c# linq ienumerable deferred-execution

在下面的代码中,我理解第二个初始化打印一个"外部"和三个"内部".但是为什么第一个根本不打印,我希望它打印一个"外面".

        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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 8

返回的可枚举实现为迭代器块(即,使用的方法yield).

迭代器块中的代码在第一次枚举之前实际上不会执行,所以如果你实际上没有对它进行任何操作,你将看不到任何事情IEnumerable.

  • 请注意,“ToArray()”会迭代可枚举对象,因为它需要检索所有值来构造数组。 (2认同)