Foreach and yield in C,

Source: Internet
Author: User
Tags finally block

Foreach and yield in C,

1. foreach

C # The Compiler converts the foreach statement to the methods and attributes of the IEnumerable interface.

foreach (Person p in persons) {     Console.WriteLine(p); }

The foreach statement is parsed into the following code segment.

Call the GetEnumerator () method to obtain an array enumeration.

In the while LOOP, As long as MoveNext () returns true, the loop continues.

Use the Current attribute to access elements in the array

IEnumerator enumerator = persons. GetEnumerator(); while (enumerator.MoveNext()) {    Person p = (Person) enumerator.Current;    Console.WriteLine(p);}

2. yield statement

Two forms of yield statements:

yield return <expression>;yield break;

Returns an element of the set using a yield return statement.

The method or attribute that contains the yield statement is the iterator. The iterator must meet the following requirements:

A. The return type must be IEnumerable, IEnumerable <T>, IEnumerator, or IEnumerator <T>.

B. It cannot have any ref or out parameters.

The yield return statement cannot be in try-catch. The yield return statement can be located in try-finally try blocks.

try              {                  // ERROR: Cannot yield a value in the boday of a try block with a catch clause                 yield return "test";              }             catch             { }               try             {                 //                  yield return "test again";             }             finally             { }              try             { }             finally             {                  // ERROR: Cannot yield in the body of a finally clause                yield return "";              }

The yield break statement can be located in a try block or catch block, but not in a finally block.

The following example uses the yield return statement to implement the code of a simple set and the foreach statement to iterate the set.

Using System; using System. collections. generic; namespace ConsoleApplication6 {class Program {static void Main (string [] args) {HelloCollection helloCollection = new HelloCollection (); foreach (string s in helloCollection) {Console. writeLine (s); Console. readLine () ;}} public class HelloCollection {public IEnumerator <String> GetEnumerator () {// yield return an element of the set and move it to the next element; yield break can stop iteration yield return "Hello"; yield return "World ";}}}

Use the yield return statement to implement classes that iterate sets in different ways:

using System;using System.Collections.Generic;namespace ConsoleApplication8{    class Program    {        static void Main(string[] args)        {            MusicTitles titles = new MusicTitles();            foreach (string title in titles)            {                Console.WriteLine(title);            }            Console.WriteLine();            foreach (string title in titles.Reverse())            {                Console.WriteLine(title);            }            Console.WriteLine();            foreach (string title in titles.Subset(2, 2))            {                Console.WriteLine(title);                Console.ReadLine();            }        }    }    public class MusicTitles    {        string[] names = { "a", "b", "c", "d" };        public IEnumerator<string> GetEnumerator()        {            for (int i = 0; i < 4; i++)            {                yield return names[i];            }        }        public IEnumerable<string> Reverse()        {            for (int i = 3; i >= 0; i--)            {                yield return names[i];            }        }        public IEnumerable<string> Subset(int index, int length)        {            for (int i = index; i < index + length; i++)            {                yield return names[i];            }        }    }}

The above motion graphs are provided by "Graph dado ".

Related Article

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.