C # iterator

Source: Internet
Author: User

Iterator Overview

An iterator is a sequence that can return values of the same type.Code.

The iterator can be used as a method, operator, or get accessors code body.

The iterator Code uses the yield return statement to return each element in sequence. Yield break terminates iteration. For more information, see yield.

Multiple iterators can be implemented in the class. Each iterator must have a unique name like any class member and can be called by client code in the foreach statement, as shown below: foreach (int x in sampleclass. iterator2 ){}

The return type of the iterator must be ienumerable, ienumerator, ienumerable <t>, or ienumerator <t>.

An iterator is a set used in foreach. In C #2.0, an iterator is used to create a set for foreach, which is easy to implement: inherits from ieumnerable and implements getenumerator ().

First, this set should be based on ienumerable (generic can be used). Next we will first implement a non-generic version iterator. The Code is as follows (the non-generic code example comes from msdn ):

 

Public class daysoftheweek: system. collections. ienumerable {string [] m_days = {"sun", "mon", "Tue", "wed", "thr", "fri", "sat"}; public system. collections. ienumerator getenumerator () {for (INT I = 0; I <m_days.length; I ++) {yield return m_days [I] ;}} class testdaysoftheweek {static void main () {daysoftheweek week = new daysoftheweek (); foreach (string day in week) {system. console. write (day + "");} console. read ();}}

 

The operation result is:

Sun mon Tue wed thr Fri Sat

WhereYied returnKeyword generation enumeration Element

The implementation code of the generic version iterator is as follows:

 

 
Static void main (string [] ARGs) {stack <int> stack = new stack <int> (); stack. items = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; foreach (int I in stack) {console. writeline (I);} console. read ();} public class Stack <t>: ienumerable <t> {public T [] items; Public ienumerator <t> getenumerator () {for (INT I = 0; I <items. length; I ++) {yield return items [I] ;}} ienumerator ienumerable. getenumerator () {return getenumerator ();}}

 

The running result is as follows:

1
2
3
4
5
6
7
8
9
10

I have never written ienumerator ienumerable when g implements the generic iterator. the getenumerator () method, so the compiler keeps reporting errors to me. (conjecture) This method should be an abstract method in the ienumerator <t> interface. The getenumerator () called in this method found through prompts in the integration environment that it is actually the ienumerator <t> getenumerator () generic method written above.

When customizing the iterator, we can use the yield break keyword to jump out of the loop. In the above example, we want to output only the items smaller than or equal to 5 and adjust the above Code, for example:

 

Public class Stack <t>: ienumerable <t>
{
Public T [] items;

Public ienumerator <t> getenumerator ()
{

For (INT I = 0; I <items. length; I ++)
{

If (convert. toint32 (items [I])> 5 ))
Yield break;

Yield return items [I];
}
}

Ienumerator ienumerable. getenumerator ()
{
Return getenumerator ();
}
}

 

 

Operation Result:

 

1
2
3
4
5

 

Iterator mechanism:

 

In fact, the iterator is only processed by the compiler layer in C #2.0. It is used to simplify the work of creating an enumeration set that can be used for foreach, with no performance changes. The generated intermediate language does not change much.

Instance: define and use the named iterator

 

Class class1
{
Public ienumerator getenumerator ()
{
For (INT I = 0; I <10; I ++)
{
Yield return I;
}
}

 

// Define a named iterator and provide parameters
Public ienumerable maxtomin (INT min, int max)
{
For (INT I = max; I> = min; I --)
{
Yield return I;
}
}

 

// Defines the attributes of an iterator type,
Public ienumerable mintomax
{
// This indicates the class instance, because the class implements getenumerator (), which is enumerable
Get {yield return this ;}
}

 

Public ienumerable getdescriptions ()
{
Yield return "this is my test ";
Yield return "Class Name Is class1 ";
Yield return "ktgu ";
}
}

 

Static void main (string [] ARGs)
{

Class1 c = new class1 ();

 

Foreach (int I in C)
{
Console. writeline (I );
}

 

Foreach (int I in C. maxtomin (1, 10 ))
{
Console. writeline (I );
}

 

Foreach (int I in C. mintomax)
{
Console. writeline (I );
}

 

Foreach (string s in C. getdescriptions ())
{
Console. writeline (s );
}
}

 

Iteration effect and key points

 

1. Iterative Abstraction: access the content of an aggregate object without exposing its internal representation.

 

2. Iterative polymorphism: provides a unified interface for Traversing different set structures to support the sameAlgorithmOperate on different collection structures.

 

3. robustness of the iterator: Changing the collection structure of the iterator while traversing will cause problems.

 

Applicability

 

1. Access the content of an aggregate object without exposing its internal representation.

 

2. Supports multiple traversal of aggregate objects.

 

3. provides a unified interface (supporting multi-state iteration) for Traversing different aggregation structures ).

 

Summary

 

The iterator mode separates the traversal behavior of the set object and abstracts an iterator class to take charge of it, so that the internal structure of the set is not exposed, allows external code to transparently access data in the collection.

Refer:
C #2.0-iterator application http://cs.alienwave.cn/Topic/1347.aspx
Http://msdn2.microsoft.com/zh-cn/library/dscyy5s0 (vs.80). aspx

 

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.