How does IEnumerable work in background

前端 未结 3 1599
天命终不由人
天命终不由人 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:14

    So, what is the collection the actual items (in the example 2*x items) reside in?

    It is not residing anywhere. There is code that will produce the individual items "on demand" when you iterate, but the 2*x numbers are not computed upfront. They are also not stored anywhere, unless you call ToList or ToArray.

    Moreover, if we were to write IEnumerable temp = Enumerable.Repeat(1, 10);, what would be the underlying collection where the 1s are stored (array, list, something else)?

    The same picture is here: the returned implementation of IEnumerable is not public, and it returns its items on demand, without storing them anywhere.

    C# compiler provides a convenient way to implement IEnumerable without defining a class for it. All you need is to declare your method return type as IEnumerable, and use yield return to supply values on as-needed basis.

提交回复
热议问题