C#迭代器与索引 简朴示例
迭代器是一种设想头脑和设想形式,在C#中能够轻易的完成一个迭代器,即完成Ienumerator接口。比方我有一个student类,现在想封装一个studentCollection,代码是如许的:
Student类:
很简朴的封装,唯逐一个字段,那就是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# 索引与迭代器的示例代码详解的内容,更多相关内容请关注ki4网(www.ki4.cn)!