سؤال

In the following code, I understand the second initialization prints one "outside" and three "inside". But why does the first does not print at all, I expect it to print one "outside".

        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;
        }
    }
}
هل كانت مفيدة؟

المحلول

The enumerable returned is implemented as an iterator block (i.e., a method that uses yield).

Code inside iterator blocks does not actually execute until they are enumerated for the first time, so you won't see anything happen if you don't actually do anything with the IEnumerable.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top