Home > Common Problem > body text

What is the core principle of yield?

coldplay.xixi
Release: 2020-07-01 15:34:07
Original
3483 people have browsed it

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.

What is the core principle of yield?

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 <expression>;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);        }    }}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template