C # iterator details

Source: Internet
Author: User

Here we only describe non-generic iterators, which are similar.

Code 1:

 

Public class Cars
{
Private int [] intArr = {1, 2, 3, 4, 5, 6, 7 };

/// <Summary>
/// Name iterator
/// </Summary>
/// <Param name = "isReverse"> whether to perform reverse iteration </param>
/// <Returns> </returns>
Public IEnumerable SortEnum (bool isReverse)
{
If (! IsReverse)
{
For (int I = 0; I <intArr. Length; I ++)
{
Yield return intArr [I];
}
}
Else
{
For (int I = intArr. Length-1; I> = 0; I --)
{
Yield return intArr [I];
}
}
} // Fun
} // Clas

Then you can iterate on the class. The Code is as follows:

Cars c = new Cars();                foreach (var item in c.SortEnum(true))                {                    Console.WriteLine(item);                }

 

 

In fact, during compilation, the compiler generates an internal class for this class, which implements the IEnumerable and IEnumerator interfaces.

 

Code 2:

Method for returning IEnumerator

Public class Cars
{
Public IEnumerator GetEnumerator ()
{
Yield return "1 ";
Yield return "2 ";
Yield return "3 ";
} // Fun
} // Clas

The sample code is as follows:

// Note that c2 does not need to call the method Cars c2 = new Cars (); foreach (var item in c2) {Console. WriteLine (item );}

 

The compiler also generates an internal class for this class, which implements the IEnumerator interface.

 

It can be seen that if you want to use the yield syntax to traverse its subelements using foreach for a type, you only need to satisfy one of the following two conditions:

1) there is a method to return IEnumerable, which is an internal yield statement.

2) there is a public IEnumerator GetEnumerator () signature method. The yield statement is used internally.

 

The reason why the above Code can be written is that the compiler helps us implement the conditions we do not have to implement manually.

 

 

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.