Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the core principle of yield

Shulou Source: shulou.com Published: 2022-06-03 03:09:24 09月14日 Update

What is the core principle of yield? I believe that many inexperienced people are at a loss about this, so this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

The core principle of yield is used in iterator blocks to provide values to enumerator objects or signal the end of iteration, whose statements can only appear in iterator blocks, which can be used as the body of methods, operators, or accessors.

The core principles of yield are:

Used in an iterator block to provide a value to an enumerator object or signal the end of an iteration.

It takes one of the following forms:

Copy the code yield return; yield break

Remarks evaluate the expression and return it as the object value of the enumerator

The expression must be implicitly converted to the yield type of the iterator.

Yield statements can only appear in an iterator block, which can be used as the body of a method, operator, or accessor.

The body of such methods, operators, or accessors is controlled by the following constraints:

Unsafe blocks are not allowed.

The argument to a method, operator, or accessor cannot be ref or out.

Yield statements cannot appear in anonymous methods.

When used with expression, yield return statements cannot appear in catch blocks or in try blocks that contain one or more catch clauses. Example in the following example, the yield statement is used in the iterator block (in this case, the method Power (int number, int power)). When the Power method is called, it returns an enumerable object that contains numeric 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);} after reading the above, have you mastered what is the core principle of yield? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Methods iterations statements principles cores objects operators operations types signals content forms more examples problems security helplessness for this code reason Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Linux Xiaomi Huawei MariaDB