Yield (C # Reference)Use the yield keyword in a statement to indicate that the method, operator, or get accessor where the keyword is located is an iterator.by using
yield to define iterators, you do not need additional explicit classes when implementing the IEnumerable and IEnumerator modes of the custom collection type (classes that preserve the enumeration state, for example see IEnumerator< T>).
The following example shows two forms of the yield statement.
Copy
Yield return <expression>;yield break;
Notes
Use the yield return statement to return one element at a time.
Use the iterator method with a foreach statement or a LINQ query. When the iterator method runs to the yield return statement, it returns an expression and retains the current position in the code. the next time the iterator function is called, execution restarts from that location.
You can use the yield break statement to terminate an iteration.
For more information about iterators, see Iterators (C # and Visual Basic).
iterator methods and get accessors
The declaration of an iterator must meet the following requirements:
-
ienumerable, ienumerable< t>, ienumerator, or Ienumerator< t>. " The return type must be IEnumerable, IEnumerable <t> , IEnumerator, or IEnumerator <t> .
-
ref or out parameters." > The declaration cannot have any ref or out https://msdn.microsoft.com/zh-cn/library/t3c3bfhx.aspx parameters.
ienumerable or ienumerator is object . If the iterator returns ienumerable< T> or ienumerator < T> There must is an implicit conversion from the type of the expression in the yield return state ment to the generic type parameter. " > The yield type of the iterator that returns IEnumerable or IEnumerator is object . If the iterator returns IEnumerable <t> or IEnumerator <t> , the yield return must be The expression type in the statement is implicitly converted to a generic type parameter.
yield return or yield break statement in methods that has the following characteristics: "> You cannot include a yield return or yield break statement in a method that has the following characteristics:
anonymous method. For more information, see Anonymous Methods (C # Programming Guide).
The method that contains the unsafe block. For more information, see Unsafe (C # Reference).
Exception Handling
The yield return statement cannot be placed in a try-catch block. The yield return statement can be placed in a try block of the try-finally statement.
The yield break statement can be in a try block or catch block, but not in a finally block.
If the foreach principal (outside the Iterator method) throws an exception, the finally block in the iterator method is executed.
Technology Implementation
The following code returns ienumerable<string>from the iterator method and then iterates through its elements.
C # Replication
ienumerable<string> elements = Myiteratormethod (); foreach (inelements) { ...}
Calling Myiteratormethod does not execute the body of the method. Instead, the call returns ienumerable<string> to the elements variable.
InforeachWhen the loop iterates, theelements calls the MoveNext method. This call will executethe main body of the Myiteratormethod until the next yield return statement is reached. The expression returned by the yield return statement not only determines the value of the element variable used by the loop body , but also determines the current property of the elements (it is the ienumerable< String>).
In each subsequent iteration of the foreach loop, the execution of the iterator body continues from where it was paused until the yield return statement is reached. The foreach loop is complete when it reaches the end of the iterator method or the yield break statement.
Example
The following example contains a forWithin the loopyield returnStatement.process creates a call to the power iterator function." Each iteration of the foreach statement body in the > process creates a call to the power iterator function. yield return statem ENT, which occurs during the next iteration of the for loop. " Each call to the iterator function continues to the next execution of the yield return statement (which occurs during the next iteration of the for Loop).
The return type of the iterator method is IEnumerable (an iterator interface type). When the iterator method is called, it returns an enumerable object that contains the power of the number.
C # Replication
PublicClass powersof2{static void Main () {//Display p Owers of 2 up to the exponent of 8: foreach (int I in Power (2, 8)) {Console.Write (public static system.collections.generic.ienumerable<< Span style= "Color:blue" >int> Power (int number, int exponent) {int result = 1; for (int i = 0; i < exponent; i++) {result = result * number;
yield
return result;}} //output:2 4 8 + +}
Example
The following example shows a get accessor that acts as an iterator. in this example, each yield return statement returns an instance of a user-defined class.
C # Replication
PublicStaticClass galaxyclass{PublicStaticvoid Showgalaxies () {var thegalaxies =New Galaxies ();foreach (Galaxy thegalaxyIn Thegalaxies.nextgalaxy) {Debug.WriteLine (Thegalaxy.name +"" + theGalaxy.MegaLightYears.ToString ());}}PublicClass Galaxies {Public system.collections.generic.ienumerable<galaxy> Nextgalaxy {get {YieldReturnNew Galaxy {Name ="Tadpole", Megalightyears = 400};Yieldreturn new Galaxy {Name = " Pinwheel ", Megalightyears = 25}; yield return new Galaxy {Name = "Milky", Megalightyears = 0}; yield return new Galaxy {Name = "Andromeda", Megalightyears = 3}; }}} public class Galaxy {public String Name {get; set;} public int megalightyears {get; Span style= "Color:blue" >set; } }}
For more information, see the C # Language specification. The language specification is the authoritative material for C # syntax and usage.
Yield (C # Reference)