Play a spin iterator

Source: Internet
Author: User

Iterator overview

Iterators are a piece of code that can return an ordered sequence of values of the same type.

An iterator can be used as the code body for a method, operator, or get accessor.

The iterator code returns each element in turn using the yield return statement. Yield break terminates the iteration. For more information, see yield.

You can implement multiple iterators in a class. Each iterator must have a unique name like any class member, and can be called by client code in a foreach statement, as follows: foreach (int x in Sampleclass.iterator2) {}

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

Iterators are collections that are used in foreach. Using iterators in c#2.0 to create a collection for foreach is simple to implement: inherit from Ieumnerable and implement GetEnumerator ().

First, this collection is based on IEnumerable (You can use generics), and the following first implements a non-generic version of the iterator. The code is as follows (the non-generic code sample is 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 results are:

Sun Mon Tue Wed Thr Fri Sat

Where the yied return keyword produces an enumeration element

The implementation code for a 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 results of the operation are as follows:

1 2 3 4 5 6 7 8 9 10

where g in implementing the generic iterator I have not written IEnumerator Ienumerable.getenumerator () This method, so the compiler has been giving me an error, (conjecture) This method should be ienumerator<t> An abstract method in the interface. While this method calls the GetEnumerator (), it is found in the integrated environment that the ienumerator<t> GetEnumerator () is actually the generic method written above.

When customizing iterators, we can use the yield break keyword to jump out of a loop. As in the above example, we want to output only items that are less than or equal to 5, and adjust the above code, such as:

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

The mechanism of the iterator:

In fact, the iterator is simply an extra layer of processing in c#2.0 through the compiler, which simplifies the work of creating an enumeration set that can be used with foreach, with no performance change. There is not much change in the intermediate language it produces.
Example: Defining and Using named Iterators

Class Class1 {public IEnumerator GetEnumerator () {for (int i = 0; i <; i++) {yield       return i; }     }

Defines a named iterator and can provide parameters public IEnumerable maxtomin (int min, int max) {for (int i = max; I >= min; i--)       {yield return i; }     }

A property that defines an iterator type, public IEnumerable Mintomax {//This represents the class instance, because the class implements the GetEnumerator (), which is an 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, ten)) {Console.WriteLine (i); }

foreach (int i in C.mintomax) {Console.WriteLine (i); }

foreach (String s in C.getdescriptions ()) {Console.WriteLine (s); }    }

Iterative effect and key points of implementation

1. Iterative abstraction: Accesses the contents of an aggregated object without exposing its internal representation.

2. Iterative polymorphism: Provides a unified interface for traversing different collection structures, enabling the same algorithm to operate on different sets of structures.

3. The robustness of an iterator is considered: traversing the same time as changing the collection structure where the iterator is located can cause problems.

Applicability

1. Accesses the contents of an aggregated object without exposing its internal representation.

2. Supports multiple traversal of an aggregated object.

3. Provides a unified interface for traversing different aggregation structures (that is, support for polymorphic iterations).

Summarize

The iterator pattern is the separation of the traversal behavior of the collection object and the abstraction of an iterator class to be responsible for not exposing the internal structure of the collection, but also allowing the external code to transparently access the data inside the collection
Reference: c#2.0-iterator application Http://cs.alienwave.cn/Topic/1347.aspx iterator (C # Programming Guide) http://msdn2.microsoft.com/zh-cn/library/ Dscyy5s0 (vs.80). aspx

Play a spin iterator

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.