c# 索引与迭代器的示例代码详解

黄舟
黄舟 原创
2017-03-04 10:16:21 1140浏览

C#迭代器与索引 简单示例

迭代器是一种设计思想和设计模式,在C#中可以方便的实现一个迭代器,即实现Ienumerator接口。例如我有一个student类,现在想封装一个studentCollection,代码是这样的:

Student类:

StudentCollection类:

很简单的封装,仅有一个字段,那就是studentList,类型是list<Student>,实现Ienumerator接口的代码我借助了studentList,因为这个类实现了这个接口,因此拿来用就好了。这样我就可以对studentCollection进行foreach遍历了:

代码说明:

1. new一个studentCollection对象,并使用初始化器一一初始化每一个student对象

2. foreach遍历每一个student

3. 取得每一个人的名字累加到字符串,然后弹出提示框显示

有其他方式实现Ienumerator这个接口吗?答案是肯定的,代码如下:


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


关于索引符以及索引符重载:

细心的读者可能已经发现了,在studentCollection类中,我定义了两个索引符:

////通过索引来访问

 public Student this[int index]
        {
            get
            {
                return studentList[index];
            }
        }

////通过学生姓名来访问

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

索引符重载机制使得封装显得更灵活,更强大。

以上就是c# 索引与迭代器的示例代码详解的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。