C # iterator (1)

Source: Internet
Author: User

Excerpted from the iterator section of. NET platform and C # Object-Oriented Programming

You must read books and take notes to understand them in a down-to-earth Manner. Otherwise, the concept of writing a program will be vague and will not be used.

The iterator is a new function in C #2.0. It is a method, get accessor or operator. This allows you to support foreach iteration in the class or structure without implementing the entire IEnumerable interface. You only need to provide an iterator to traverse the data structure in the class. When the compiler detects the iterator, the Current, MoveNext, and Dispose methods of the IEnumerable or IEnumerable interfaces are automatically generated.

  1. Overview

    An iterator is a piece of code that can return an ordered sequence of values of the same data type. It can be used as a method, operator, or get accessors.

    The iterator Code uses the yield return statement to return each element at a time. yield break terminates the iteration.

    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, for example:

    Foreach (int x in SampleClass. Iterator2 ){}

    The return type of the iterator must be IEnumerable, IEnumerator, IEnumerable, or IEnumerator.

    The yield keyword is used to specify the returned value. The current position will be saved when the yield return Statement is reached. The next time the iterator is called, it will be executed again from this position.

    The iterator is particularly useful for collection classes. It provides a simple method to iterate infrequently used data structures, such as binary trees.

  2. Use
    The most common method to create an iterator is to implement the GetEnumerator method for the IEnumerable interface, such:
       1:  public System.Collections.IEnumerator GetEnumerator()
       2:  {
       3:      for(int i=0;i<max;i++)
       4:      {
       5:          yield return i;
       6:      }
       7:  }

    The existence of the GetEunmerator method makes the type an enumerated type and allows the use of foreach statements. If the above method is part of the class definition of ListClass, you can use foreach for this class, such:

    static void Main()
    {
        foreach(int i
        ListClass listClass1=new ListClass();
     in listClass1)
        {
            System.Console.WriteLine(i);
        }
    }

    The foreach statement calls ListClass. GetEnumerator () and uses the returned enumerated number to cyclically access the value.

    You can also use the named iterator to cyclically access the same data set in different ways. For example, you can provide an iterator that returns elements in ascending or descending order. The iterator can contain parameters to allow the client to control all or part of the iteration behavior. The following iterator uses the named iterator SampleIterator to implement the IEnumerable interface:

    //Implementing the enumerable pattern
    public System.Collections.IEnumerable SampleIterator(int start,int end)
    {
        for(int i=start;i<=end;i++)
        {
            yield return i;
        }
    }

    The calling method of the named iterator is as follows:

    ListClass test=new ListClass();
    foreach(int n in test.SampleIterator(1,10))
    {
        System.Console.WriteLine(n);
    }

    You can use multiple yield statements in the same iterator, for example:

    public System.Collections.IEnumerator GetEunmerator()
    {
        yield return "With an iterator";
        yield return "more than one";
        yield return "value can be returned";
        yield return ".";
    }

    Then you can use the following foreach statement to output the result:

    foreach(string element in new TestClass())
    {
        System.Console.Write(element);
    }

    Display:

    With an iterator more than one value can be returned.

    After each foreach statement loop (or for IEnumerator. in the MoveNext direct call), the next iterator code body starts after the previous yield statement and continues the next statement until it reaches the end of The iterator body or encounters the yield break statement.

  3. Yield statement

    The yield statement is used in the iterator block to provide a value for the enumerated number object or send an iteration end signal. The form is as follows:

    yield return expression;
    yield break;

    The expression parameter is calculated and returned as an enumerated number object value. It must be implicitly converted to the yield type of the iterator.

    The yield statement can only appear in the iterator block. This block can be used as a method, operator, or accessors. This type of body is subject to the following constraints:

    1. Insecure blocks are not allowed

    2. The parameter cannot be ref or out.

    3. When used together with expression, the yield return statement cannot appear in catch statement blocks or try blocks containing one or more catch clauses.

    The following iterator blocks (int number, int Power) method) use the yield statement. When the power method is called, an enumerative object containing the numeric Power is returned. Note that the return type of this method is IEnumerable (an iterator interface type)

       1:  //yield-example.cs
       2:  using System;
       3:  using System.Collections;
       4:  public class List
       5:  {
       6:      public static IEnumerable Power(int number,int exponeng)
       7:      {
       8:          int counter=0;
       9:          int result=1;
      10:          while(counter++<exponent)
      11:          {
      12:              result=result*number;
      13:              yield return result;
      14:          }
      15:      }
      16:      static void Main()
      17:      {
      18:          foreach(int i in Power(2,8))
      19:          {
      20:              Console.Write("{0}",i);
      21:          }
      22:      }
      23:  }

    The output is as follows:

    2 4 8 16 32 64 128 256

  4. Iteration Program

    Use the C # iterator in the city collection:

    public class CityCollection:IEnumerable<string>
    {
        string[] m_Cities=new {"New York","Paris","London"};
        public IEnumerator<string> GetEnumerator()
        {
            for(int i=0;i<m_Cities.Length;i++)
                yield return m_Cities[i];
            }
        }
    }

    Use the C # iterator in a non-General set:

    public class CityCollection:IEnumerable
    {
        string[] m_Cities=new {"New York","Paris","London"};
        public IEnumerator GetEnumerator()
        {
            for(int i=0;i<m_Cities.Length;i++)
                yield return m_Cities[i];
            }
        }
    }

    In addition, you can use the C # iteration program in a general set, when a general set and iteration program are used, the compiler knows the specific type used by IEnumerable <ItemType> In the foreach loop from the type used by the declared set.

Still cannot solve it, read a book again

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.