Example code for C # indexes and iterators

Source: Internet
Author: User

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)!

  • 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.