The "yield" in C # uses
Yield is the syntax sugar that C # implements to simplify traversal operations, and we know that if you want a type to support traversal you have to implement the System interface IEnumerable, which is cumbersome to write a lot of code to support the true traversal function. Examples Show
using System;
Using System.Collections.Generic;
Using System.Collections;
Using System.Linq;
Using System.Text;
Namespace
{
Class Program
{
static void Main (string[] args)
{
Hellocollection hellocollection = new Hellocollection ();
foreach (string s in hellocollection)
{
Console.WriteLine (s);
}
Console.readkey ();
}
}
//
Public class Hellocollection:ienumerable
//
{
//
Public IEnumerator GetEnumerator ()
//
{
//
yield return "Hello";
//
yield return "world";
//
}
//}
public class Hellocollection:ienumerable
{
Public IEnumerator GetEnumerator ()
{
Enumerator enumerator = new Enumerator (0);
return enumerator;
}
public class Enumerator:ienumerator, IDisposable
{
private int state;
Private object Current;
Public Enumerator (Int.)
{
This.state = State;
}
public bool MoveNext ()
{
Switch (state)
{
Case 0:
Current = "Hello";
state = 1;
return true;
Case 1:
Current = "World";
state = 2;
return true;
Case 2:
Break
}
return false;
}
public void Reset ()
{
throw new NotSupportedException ();
}
public Object Current
{
get {return current;}
}
Public void Dispose ()
{
}
}
}
}
The section above comments refers to "yield return", which functions like all of the following code! You can see that if you don't apply yield, you need a lot of code to support traversal operations.
The yield return represents the data returned during the next iteration in the iteration, in addition to yield break, which represents jumping out of the iteration, in order to understand the difference between the two we look at the following example
class A:ienumerable
{
Private int[] array = new INT[10];
Public IEnumerator GetEnumerator ()
{
for (int i = 0; i <; i++)
{
Yield return array[i];
}
}
}
If you only want users to access the first 8 data of an array, you can make the following modifications. Yield break is used and the function is modified as follows
Public IEnumerator GetEnumerator ()
{
for (int i = 0; i <; i++)
{
if (I < 8)
{
Yield return array[i];
}
Else
{
Yield break;
}
}
}
This will return only the first 8 data.
"Yield" in C # uses