Home >Common Problem >What is the core principle of yield?
The core principle of yield is that it is used in the iterator block to provide values to the enumerator object or to signal the end of iteration. Its statements can only appear in the iterator block, which can be used as a method, operator or The body of the accessor.
The core principle of yield is:
is used in the iterator block to add the enumerator object Provide a value or signal the end of the iteration.
Its form is one of the following:
Copy codeyield return 41256fb142f22f4bfc3f76fe922f5535;yield break;
Remarks Calculates expressions and returns them in the form of enumerator object values;
expression
must be implicitly convertible to iteration The yield type of the device.
The yield statement can only appear within an iterator block, which can be used as the body of a method, operator, or accessor.
The body of such a method, operator, or accessor is governed by the following constraints:
Unsafe blocks are not allowed.
Parameters to methods, operators, or accessors cannot be ref
or out
.
The yield statement cannot appear in an anonymous method.
When used with expression, a yield return statement cannot appear in a catch block or in a try block containing one or more catch clauses. Example In the following example, the yield statement is used in an iterator block (here the method Power(int number, int power)). When the Power method is called, it returns an enumerable object containing numbers raised to powers.
Note that the return type of the Power method is IEnumerable
(an iterator interface type).
yield-example.csusing System;using System.Collections;public class List{ public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; yield return result; } } static void Main() { // Display powers of 2 up to the exponent 8: foreach (int i in Power(2, 8)) { Console.Write("{0} ", i); } }}
The above is the detailed content of What is the core principle of yield?. For more information, please follow other related articles on the PHP Chinese website!