c#迭代器与索引 简单示例
迭代器是一种设计思想和设计模式,在c#中可以方便的实现一个迭代器,即实现ienumerator接口。例如我有一个student类,现在想封装一个studentcollection,代码是这样的:
student类:
studentcollection类:
很简单的封装,仅有一个字段,那就是studentlist,类型是list1f479e44f2c9bd2301ecbd2b69e4d7bf,实现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# 索引与迭代器的示例代码详解的内容。