Detailed explanation of sample code of c# index and iterator

黄舟
Release: 2017-03-04 10:16:21
Original
1454 people have browsed it

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 list, 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关键字实现迭代器
            }
        }
Copy after login


##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];
            }
        }
Copy after login

////Access by student name

##

 public Student this[string name]
        {
            get { return studentList.Single(s => s.StudentName == name); }
        }
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template