【问题标题】:About deferred execution of IEnumerable关于 IEnumerable 的延迟执行
【发布时间】:2013-01-25 22:54:33
【问题描述】:

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

        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;
        }
    }
}

【问题讨论】:

    标签: c# linq ienumerable deferred-execution


    【解决方案1】:

    返回的可枚举实现为iterator block(即使用yield的方法)。

    迭代器块中的代码在第一次被枚举之前不会真正执行,因此如果您实际上不对IEnumerable 执行任何操作,您将不会看到任何事情发生。

    【讨论】:

    • 请注意,它是ToArray() 迭代可枚举的,因为它需要检索所有值来构造数组。
    • 是的,但是 Console.WriteLine("outside") 在迭代器块之外。为什么它也不打印。
    • @hongpei:迭代器块是整个方法的调用。一旦它开始运行,它就会继续运行,直到它到达yield。您建议它应该立即开始运行并停止......在哪里?为什么?
    • 我有点想迭代器块应该是第一个产量和最后一个产量之间的区域。
    • 但是我上面的想法会导致无法定义迭代器块,不是吗?
    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多