C uses the foreach statement to traverse the method of collection type

  • 2021-07-03 00:46:08
  • OfStack

This article illustrates how C # uses foreach statements to iterate through collection types. Share it for your reference. The details are as follows:

Here is a demonstration of how to implement a collection class that can be used with foreach statement 1


using System;
using System.Collections;
public class Tokens: IEnumerable
{
  private string[] elements;
  Tokens(string source, char[] delimiters)
  {
   elements = source.Split(delimiters);
  }
  // IEnumerable  Interface implementation: 
  public TokenEnumerator GetEnumerator() //  Non  IEnumerable  Version 
  {
   return new TokenEnumerator(this);
  }
  IEnumerator IEnumerable.GetEnumerator() // IEnumerable  Version 
  {
   return (IEnumerator) new TokenEnumerator(this);
  }
  //  Internal class implementation  IEnumerator  Interface: 
  public class TokenEnumerator: IEnumerator
  {
   private int position = -1;
   private Tokens t;
   public TokenEnumerator(Tokens t)
   {
     this.t = t;
   }
   public bool MoveNext()
   {
     if (position < t.elements.Length - 1)
     {
      position++;
      return true;
     }
     else
     {
      return false;
     }
   }
   public void Reset()
   {
     position = -1;
   }
   public string Current //  Non  IEnumerator  Version: Type safe 
   {
     get
     {
      return t.elements[position];
     }
   }
   object IEnumerator.Current // IEnumerator  Version: Return object 
   {
     get
     {
      return t.elements[position];
     }
   }
  }
  //  Test mark  TokenEnumerator
  static void Main()
  {
   Tokens f = new Tokens("This is a well-done program.", 
     new char [] {' ','-'});
   foreach (string item in f) //  To put  string  Change to  int
   {
     Console.WriteLine(item);
   }
  }
}

I hope this article is helpful to everyone's C # programming.


Related articles: