The foreach traversal is a common feature of C #, and this article demonstrates the way in which C # uses the yield keyword to enable a custom collection to implement a foreach traversal. The steps are as follows:
In general, when we create a custom collection, we can only implement the IEnumerable interface (and possibly the IEnumerator interface) in order for it to support the foreach traversal.
But we can also implement a foreach traversal by using an iterator method built with the yield keyword, and the custom collection does not implement the IEnumerable interface
Attention:
Although you do not need to implement the IEnumerable interface, the iterator's method must be named GetEnumerator () and the return value must be of type IEnumerator.
The instance code and a simple comment are described below:
Class person{public string Name; public void Sayhi () { Console.WriteLine (' Hello: {0} ', this. Name);} } A very simple custom collection (--Simple to add, delete, indexer, etc.) does not implement the IEnumerable interface Class 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 The return function is to return an element of the collection and move to the next element yield return item;}} Class program{ static void Main (string[] args) { personlist list = new Personlist (); foreach (person item in list) { item. Sayhi (); } Console.ReadLine (); }}
Interested readers can do a hands-on test of this example code, I believe there will be a new harvest.
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
C # uses the yield keyword to enable a custom collection to implement a foreach traversal method
This address: http://www.paobuke.com/develop/c-develop/pbk23657.html
About C # programming how to get pictures in a resource file examples of simple implementations of timers in C # 30 minutes Quick Mastery of C # 6.0 knowledge points WPF ListView control custom Layout Usages instance
C # Design Pattern Series Tutorial-singleton mode C # to determine whether the operating system is WIN8 or above version C # Judging whether a program is running with Administrator privileges code example C # uses SqlBulkCopy to bulk copy data to a datasheet
C # uses the yield keyword to enable a custom collection to implement a foreach traversal method