Home  >  Article  >  Backend Development  >  Detailed explanation of examples of foreach and yield in C#

Detailed explanation of examples of foreach and yield in C#

黄舟
黄舟Original
2017-10-05 15:31:262003browse

1. foreach

The C# compiler will convert the foreach statement into the methods and properties of the IEnumerable interface.


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

The foreach statement will be parsed into the following code segment.

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

In the while loop, as long as MoveNext() returns true, the loop will continue

Use the Current property 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 statement:


yield return <expression>;yield break;

Use a yield return statement to return an element of the collection

The method or property containing the yield statement is an iterator. Iterators must meet the following requirements

a. The return type must be IEnumerable, IEnumerable8742468051c85b06f0a0af9e3e506b5c, IEnumerator, or IEnumerator8742468051c85b06f0a0af9e3e506b5c.

b. It cannot have any ref or out parameters

The yield return statement cannot be located in a try-catch block. The yield return statement can be located in the try block of try-finally


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 the try block or catch block, but cannot be located below the finally block

Examples are code that uses a yield return statement to implement a simple collection, and a foreach statement to iterate over a collection


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语句返回集合的一个元素,并移动到下一个元素上;yield break可以停止迭代
            yield return "Hello";            yield return "World";
        }
    }
}

A class that uses a yield return statement to iterate a collection 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 is the detailed content of Detailed explanation of examples of foreach and yield in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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