Generally, when we create a custom set, we can only implement the ienumerable interface (which may also implement the ienumerator Interface) to support foreach traversal)
However, we can also use the iterator Method built with the yield keyword to implement foreach traversal, And the custom set does not need to implement the ienumerable interface.
Note: although you do not need to implement the ienumerable interface, the method of the iterator must be named getenumerator (), and the returned value must also be of the ienumerator type.
The instance code and simple instructions are as follows:
1 class person 2 {3 Public string name; 4 Public void sayhi () 5 {6 console. writeline ("Hello: {0}", this. name); 7} 8} 9 // very simple custom set (-simple to add, delete, index, and other functions are not implemented) this class does not implement the ienumerable interface 10 class personlist11 {12 person [] pers = new person [4]; 13 public personlist () 14 {15 pers [0] = new person () {name = "1"}; 16 pers [1] = new person () {name = "2"}; 17 pers [2] = new person () {name = "3"}; 18 pers [3] = new person () {name = "4 "}; 19 20} 21 // simple iterator Method 22 public ienumerator getenumerator () 23 {24 25 foreach (person item in pers) 26 {27 // yield return is used to return an element of the set and move it to 28 yield return item on the next element; 29} 30 31} 32} 33 class program34 {35 static void main (string [] ARGs) 36 {37 personlist list = new personlist (); 38 foreach (person item in List) 39 {40 item. sayhi (); 41} 42 console. readline (); 43} 44}