C # How to Implement the ienumerable and ienumerator interfaces of a custom set and use foreach to access the custom set

Source: Internet
Author: User

Discussion:

 Static   Void Main ( String  [] ARGs ){  Int [] Array = New   Int [] { 5 ,4 , 3 , 2 , 1  };  Foreach ( Int I In  Array) console. writeline (  "  Number:  " + I); console. readkey ();}  /* ** ------------- Execution result ------------- * Number: 5 * Number: 4 * Number: 3 * Number: 2 * Number: 1 * ------------- execution result -------------  */ 

Q: Why can I use foreach to traverse all elements in the array?

Cause: the array is an enumerative type. It can provide an enumerative number as needed. The enumerated number can return the elements of the requested array in sequence. The foreach structure is designed to be used with enumeration types. If the traversal object of foreach is of the enumerable type, she will execute the following behavior:

    1. Call the getenumerator method to obtain the enumerated number of an object (for example, an array) (that is, the element value in an array)
    2. Request each item from the enumerated number and traverse it as an iteration.

Because the array type is enumerable, I use the ienumerator interface to implement the enumeration number to simulate the loop traversal of foreach.

ImplementationCodeAs follows:

 Static   Void Main ( String [] ARGs ){  Int [] Array = New   Int [] { 5 , 4 , 3 , 2 , 1  }; Ienumerator IE = Array. getenumerator (); //  Retrieve enumerative number      While (Ie. movenext ()) // Move the next item  {  //  At first, the enumeration number is located before the first element in the set. At this position, the current attribute is not defined.  //  Therefore, before reading the current value, you must call the movenext method to advance the number of enumerations to the first element of the set.          Int I = ( Int ) IE. Current; //  Get current item Console. writeline ( "  Number:  " + I );}} /*  ** ------------- Execution result ------------- * Number: 5 * Number: 4 * Number: 3 * Number: 2 * Number: 1 * ------------- execution result -------------  */ 

Implement ienumerable and ienumerator Interfaces

The following example shows how to implement the ienumerable and ienumerator interfaces of a custom set. In this example, no members of these interfaces are explicitly called, but they are implemented to support using foreach to access the set cyclically.

Key points:

    1. Display the getenumerator member function that implements the ienumerable Interface
    2. Displays the current, reset (), and movenext () implementations of the ienumerator interface ()

:

Using  System;  Using  System. collections;  Using  System. Collections. Generic;  Using  System. LINQ;  Using  System. text;  Using  System. Threading. tasks;  Namespace  Leleapplication1 {  // Implement the ienumerator Interface      Public   Class  Personienumerator: ienumerator {  String  [] Person;  Int Position =- 1  ;  Public Personienumerator ( String  [] Thepersons) {person = New   String [Thepersons. Length];  For ( Int I = 0 ; I <thepersons. length; I ++ ) {Person [I] = Thepersons [I];}  //  Feature 1 of the ienumerator Interface          Public   Object  Current {  Get { Return Person [position] ;}}  //  Features 2 of the ienumerator Interface          Public   Bool  Movenext (){  If (Position <person. Length- 1  ) {Position ++ ;  Return   True  ;}  Else                 Return   False  ;}  //  Features 3 of the ienumerator Interface          Public   Void  Reset () {position =- 1  ;}}  //  Implement the ienumerable Interface      Public   Class  Mypersons: ienumerable { String [] Strarr = New   String [] { "  Zhou xingchi  " , "  Mo Yan  " , "  Beckham  " , "  Lin Zhiying  "  }; //  Returns an object of the ienumerator type.          Public  Ienumerator getenumerator (){  Return   New  Personienumerator (strarr );}}  Class  Program {  Static   Void Main ( String  [] ARGs) {mypersons MP = New Mypersons ();  Foreach ( String Name In  MP) {console. writeline (  "  {0}  "  , Name) ;}console. readkey ();}}  /*  ** ------------- Execution result ------------- * Zhou xingchi * Mo Yan * Beckham * Lin Zhiying * ----------- execution result -------------  */ } 

 

Note: The foreach statement in C # Hides the complexity of enumeration numbers. Therefore, we recommend that you use foreach instead of operating the enumerated number directly.

OriginalArticle, Reprinted please indicate the source:Http://www.cnblogs.com/hongfei

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.