C # the principle that the class can be traversed through foreach,

Source: Internet
Author: User

C # the principle that the class can be traversed through foreach,

Conditions that must be met first for the class to be traversed using foreach

1. The class must implement the public method public IEnumerator GetEnumerator () {}. you can also inherit the IEnumerable interface to implement this method.

2. The class implements public IEnumerator GetEnumerator () {}. to return an object for traversal, this object must inherit the IEnumerator interface.

1 class Program 2 {3 static void Main (string [] args) 4 {5 Person p = new Person (); 6 p [0] = "James "; 7 p [1] = "xiao hong"; 8 p [2] = "Xiao Fang"; 9 p [3] = "Xiao Long"; 10 for (int I = 0; I <p. count; I ++) 11 {12 Console. writeLine (p [I]); 13} 14 15 Console. writeLine ("========================================== ===== "); 17 foreach (var name in p) 18 {19 Console. writeLine (name); 20} 21 Console. readKey (); 22} 23} 24 25 internal class Person: IEnumerable26 {27 private List <string> listStudent = new List <string> (); 28 public int Count {29 get {return listStudent. count;} 30} 31 32 public string this [int index] 33 {34 get {return listStudent [index];} 35 set36 {37 if (index> = Count) 38 {39 listStudent. add (value); 40} 41 else42 {43 listStudent [index] = value; 44} 45} 46} 47 48 49 50 public IEnumerator GetEnumerator () 51 {52 return new PersonIEnumerator (listStudent); 53} 54} 55 56 class PersonIEnumerator: IEnumerator57 {58 public PersonIEnumerator (List <string> _ listName) 59 {60 listName = _ listName; 61} 62 63 private List <string> listName; 64 private int index =-1; 65 66 public object Current67 {68 get {return listName [index];} 69} 70 71 public bool MoveNext () 72 {73 index ++; 74 if (index> = listName. count) 75 {76 return false; 77} 78 else79 {80 return true; 81} 82} 83 84 public void Reset () 85 {86 index =-1; 87} 88}

 

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.