C #: Introduction to foreach and yield statements

Source: Internet
Author: User
Tags finally block

1. foreach statement

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

Copy codeThe Code is as follows: 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

Copy codeThe Code is as follows: IEnumerator enumerator = persons. GetEnumerator ();
While (enumerator. MoveNext ())
{
Person p = (Person) enumerator. Current;
Console. WriteLine (p );
}

2. yield statement

• Two forms of yield statements:

Copy codeThe Code is as follows: yield return <expression>;
Yield break;

• Use a yield return statement to return an element of the Set
• The method or attribute that contains the yield statement is an 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 placed in try-catch. The yield return statement can be located in try-finally try blocks.

Copy codeThe Code is as follows: 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.

Copy codeThe Code is as follows: 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 ()
{
// The yield return Statement returns an element of the set and moves 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:

Copy codeThe Code is as follows: 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];
}
}
}
}

Output:

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.