C # iterators and indexes simple example
iterators is a design idea and design pattern, C # can easily implement an iterator that implements the Ienumerator interface. For example I have a student class and now want to encapsulate a studentcollection, the code is this:
Student class:
studentcollection class:
in a very simple package, there is only one field, and that is Studentlist, type is list<student> to achieve Ienumerator interface code I took advantage of the studentlist , because this class implements this interface, so it's good to use it. So I can do A foreach traversal of the studentcollection:
Code Description:
1. new a studentcollection object and initializes each one with the initializer one by one student Object
2. iterate through each of the student with foreach
3. get each person's name added to the string, and then a pop-up prompt box appears
There are other ways to implement Ienumerator this interface? The answer is yes, the code is as follows:
Public IEnumerator GetEnumerator () { foreach (Student s in studentlist) { yield return s;//// Implementing an iterator with the yield keyword } }
About index characters and indexer overloading:
The attentive reader may have found out, in studentcollection class, I have defined two index characters:
//// Access by index
Public Student This[int Index] { get { return studentlist[index]; } }
//// access by student name
Public Student this[string Name] { get {return Studentlist.single (s = = S.studentname = name);} }
The overloaded index mechanism makes encapsulation more flexible and more powerful.
The above is the example code of C # Index and iterator in detail, more relevant content please follow topic.alibabacloud.com (www.php.cn)!