通过一个例子来看
-------------------------------------------------------Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication6
{
public class Student:IEnumerable
{
//数组
public string[] s;
//索引器
public int i;
public Student(string[] str)//构造函数,初始化数组
{
s = str;
}
public IEnumerator GetEnumerator()//迭代器
{
return s.GetEnumerator();
}
}
}
-------------------------------------------------------StiAll.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication6
{
public class StiAll:IEnumerator
{
//student对象
Student s;
//游标
int i = -1;
public StiAll(Student ss)//构造函数,初始化student对象
{
this.s = ss;
}
public object Current//获取当前的项(只读属性)
{
get { return s.s[i]; }
}
public bool MoveNext()//将游标的位置向前移动
{
if (i<s.s.Length-1)//如果在s数组的长度范围之内就返回true
{
i++;
return true;
}
else
{
return false;
}
}
public void Reset()//初始化游标
{
i = -1;
}
}
}
-------------------------------------------------------主程序
Student s = new Student(new string[] { "吕蒙", "周泰", "黄盖" });//实例化Student对象
//第一种方式遍历
foreach (var item in s)
{
Console.WriteLine(item);//输出吕蒙,周泰,黄盖
}
//第二种方式遍历
StiAll sa = new StiAll(s);
while (sa.MoveNext())
{
Console.WriteLine(sa.Current);//输出吕蒙,周泰,黄盖
}
Console.ReadKey();
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。