参考网址:https://blog.csdn.net/qq_39806817/article/details/115024666
一、IEnumerable简单介绍
IEnumerable是可枚举类型,一般在迭代时应用广泛,如foreach中要循环访问的集合或数组都实现了IEnumerable接口。只要能够遍历,都直接或间接实现了IEnumerable接口。如:String类型的对象,可遍历,输出时以字符输出,间接实现了IEnumerable接口,"OOP"遍历打印就是'O','O','P';又如int类型没有实现IEnumerable接口,就无法依赖foreach遍历。
二、实现IEnumerable接口
现以一个实例遍历数组:
IEnumerableTest enumerableTest = new IEnumerableTest();
enumerableTest.Show();
-------------------------------------------------------
public class IEnumerableTest
{
DemoIEnumerable demoIEnumerable = new DemoIEnumerable();
public void Show()
{
foreach (var item in demoIEnumerable)
{
Console.WriteLine(item);
}
}
}
public class DemoIEnumerable : IEnumerable
{
public IEnumerator GetEnumerator()
{
string[] students = new[] { "瑶瑶1", "瑶瑶2", "瑶瑶3" };
return new TestEnumerator(students);
}
}
public class TestEnumerator : IEnumerator
{
private string[] _students;
//元素下标
private int _position = -1;
public TestEnumerator(string[] students)
{
this._students = students;
}
//public object Current => throw new NotImplementedException();
public object Current
{
get
{
if (_position == -1 || _position >= _students.Length)
{
throw new InvalidOperationException();
}
return _students[_position];
}
}
public bool MoveNext()
{
if (_position < _students.Length - 1)
{
_position++;
return true;
}
return false;
}
public void Reset()
{
_position = -1;
}
}
上面的实例执行foreach步骤:首先进入DemoIEnumerable类执行GetEnumerator()方法,然后初始化_position=-1,接着执行TestEnumerator类的构造函数,然后返回进入in,执行TestEnumerator类的MoveNext()方法,判断下标(_position)是否越界,如没有越界,下标自动加1,并返回true,然后获取TestEnumerator类的Current属性,返回对应下标的值,依次迭代,获取数组的值,直至结束。