How does IEnumerable work in background

前端 未结 3 1559
天命终不由人
天命终不由人 2021-01-15 08:54

I am wandering about the more in-depth functionality of the IEnumerable interface.

Basically, it works as an intermediary step in execution. Fo

3条回答
  •  囚心锁ツ
    2021-01-15 09:22

    Implementation shouldn't matter. All these (LINQ) methods return IEnumerable, interface members are the only members you can access, and that should be enough to use them.

    However, if you really have to know, you can find actual implementations on http://sourceof.net.

    • Enumerable.cs

    But, for some of the methods you won't be able to find explicit class declaration, because some of them use yield return, which means proper class (with state machine) is generated by compiler during compilation. e.g. Enumerable.Repeat is implemented that way:

    public static IEnumerable Range(int start, int count) {
        long max = ((long)start) + count - 1;
        if (count < 0 || max > Int32.MaxValue)
            throw Error.ArgumentOutOfRange("count");
        return RangeIterator(start, count); 
    }
    
    static IEnumerable RangeIterator(int start, int count) {
        for (int i = 0; i < count; i++)
            yield return start + i;
    }
    

    You can read more about that on MSDN: Iterators (C# and Visual Basic)

提交回复
热议问题