. NET yield return

Source: Internet
Author: User

    Yield is used in an iterator block to provide a value to an enumerator object or to emit an iterative end signal. It is in the form of one of the following: yield return <expression>;yield break; Evaluates an expression and returns it as an enumerator object value, and expression must be implicitly convertible to the yield type of the iterator. The yield statement can only appear in a 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 controlled by the following constraints: L do not allow unsafe blocks.       The parameters of the L method, operator, or accessor cannot be ref or out.       The yield statement cannot appear in an anonymous method. When used with expression, the yield return statement cannot appear in a catch block or in a try block that contains one or more catch clauses. Example in the following example, the yield statement is used in the iterator block (here is method Power (int number, int power). When the power method is called, it returns an enumerable object that contains the power of a number. Note The return type of the Power method is IEnumerable (an iterator interface type). Using system;using system.collections.generic;using system.linq;using system.text; Using System.Collections;        Namespace mvcusedkeywords{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 (string[] args) {         Show 2 X-side (1<=x<=8) IEnumerable t = Power (2, 8);            foreach (int i in t) {Console.Write ("{0}", i); }}} Results: 2 4 8 16 32 64 128 256

. NET yield return

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.