Home >Backend Development >C#.Net Tutorial >Detailed explanation of sample code of c# index and iterator

Detailed explanation of sample code of c# index and iterator

黄舟
黄舟Original
2017-03-04 10:16:211457browse

C

is a design idea and design pattern. In C#, an iterator can be easily implemented, that is, Ienumeratorinterface. For example, I have a student class, and now I want to encapsulate a studentCollection. The code is as follows:

Student Class:

StudentCollection Class:

Very simple encapsulation, only There is a field, that is studentList, the type is list1f479e44f2c9bd2301ecbd2b69e4d7bf, and implements Ienumerator I used the interface code with the help of studentList, because this class implements this interface, so just use it. In this way, I can foreach traverse studentCollection:

Code description:

##1. newA studentCollection object, and use an initializer to initialize each one by one studentObject

2.       Use foreach to traverse each student

3. ## 取 3 3 3 3 3 3 3 3 3 to the string, and then pop up the prompt box display #

Is there any other way to implement the Ienumerator interface? The answer is yes, the code is as follows:


##

public IEnumerator GetEnumerator()
        {
            foreach (Student s in studentList)
            {
                yield return s;////使用yield关键字实现迭代器
            }
        }


##About index symbol and index symbol overloading:

Careful readers may have discovered that in the studentCollection class , I defined two index characters:

////Access through 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 index overloading mechanism enables encapsulation Appear more flexible and powerful.

## The above is a detailed explanation of the sample code of c# index and iterator For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn