Foreach traversal is a common function in C#, and this article shows the method of C# using the yield keyword to enable custom collections to implement foreach traversal through examples. The specific steps are as follows:
Generally speaking, when we create a custom collection, in order to support foreach traversal, we can only implement the IEnumerable interface (maybe also need to implement the IEnumerator interface)
However, we can also implement foreach traversal by using the iterator method built with the yield keyword, and custom collections do not need to implement the IEnumerable interface
Notice:Although the IEnumerable interface is not required, the iterator method must be named GetEnumerator(), and the return value must also be of IEnumerator type.
The example code and simple comments are explained as follows:
class Person { public string Name; public void SayHi() { ("Hello: {0}",); } } // Very simple custom collection (---Simple to add, delete, indexer and other functions are not implemented) This class does not implement the IEnumerable interfaceclass PersonList { Person[] pers =new Person[4]; public PersonList() { pers[0] = new Person() { Name = "1" }; pers[1] = new Person() { Name = "2" }; pers[2] = new Person() { Name = "3" }; pers[3] = new Person() { Name = "4" }; } //Simple iterator method public IEnumerator GetEnumerator() { foreach (Person item in pers) { //yield return function is to return an element of the collection and move it to the next element yield return item; } } } class Program { static void Main(string[] args) { PersonList list = new PersonList(); foreach (Person item in list) { (); } (); } }
Interested readers can test the example code of this article, and I believe there will be new gains.