linq-IEnumerable,IEnumerator


A: linq foundation necessary IEnumerable, IEnumerator


linq query must be set must implement both interfaces.


《1》 IEnumerable

GetEnumerator Method


"2" Current and the MoveNext () attribute, Reset method


Two: an iterative basis

1. Because of this IEnumerable, IEnumerator interfaces, our collection can iterate can iterate, we can use the select and select lexical extension methods


2. foreach syntax sugar

Who knows what foreach of MSIL that? ? ?


"1" profound understanding of the foreach syntax sugar

.locals init ([0] class [mscorlib]System.Collections.Generic.List`1<int32> nums,
[1] class [mscorlib]System.Collections.Generic.List`1<int32> V_1,
[2] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<int32> V_2,
[3] int32 num)


We found that more than a temporary variable, is a Enumerator <int32> type variable V_2


var nums = new List<int>() { 1, 2 };

var MyEnumerator = nums.GetEnumerator();

try
{
while (MyEnumerator.MoveNext())
{
var num = MyEnumerator.Current;

Console.WriteLine(num);
}
}
finally
{
MyEnumerator.Dispose();
}

//foreach (var num in nums)
//{
// Console.WriteLine(num);
//}

Three: yield lexical exploration

Before understanding the lexical, we need to know a class: Enumerator

This class is actually a package on the list were, in essence, the so-called movenext and current operations are carried out on the list.


MSIL code generated lexical yield:

.class auto ansi sealed nested private beforefieldinit '<GetNums>d__1'
extends [mscorlib]System.Object
implements class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>,
[mscorlib]System.Collections.IEnumerable,
class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>,
[mscorlib]System.IDisposable,
[mscorlib]System.Collections.IEnumerator

In fact, <GetNums> d__1 and Enumerator is actually the same.

to yield lexical and we generate a system-defined Enumerator having the same functional class.

Guess you like

Origin www.cnblogs.com/Spinoza/p/11621637.html