c# IEnumerable--扩展方法
namespace Linq
{
/// <summary>
/// IEnumerable可枚举类---可迭代类型
/// IEnumerator枚举器
///
/// 只要实现了IEnumerable接口,就可以对他进行遍历
/// yield关键词 他做了什么工作?他是一个迭代器,它相当于实现了IEnumerator枚举器
/// </summary>
class IEnumerableShow
{
public void Show()
{
int[] array = { 1, 2, 3, 4, 5, 6 };
int i = 1;
string str = "ANT编程";
Student student = new Student { ID = 1 };
foreach (var item in student)
{
Console.WriteLine(item);
}
}
}
class Student:IEnumerable
{
public int ID { get; set; }
public IEnumerator GetEnumerator()
{
yield实现了IEnumerator接口
//yield return "ANT编程1";
//yield return "ANT编程2";
//yield return "ANT编程3";
string[] student = { "ANT编程1" , "ANT编程2" , "ANT编程3" };
return new StudentEnumerator(student);
}
}
internal class StudentEnumerator : IEnumerator
{
private string[] _student;
int _position = -1;
public StudentEnumerator(string[] student)
{
this._student = student;
}
public object Current
{
get
{
if (_position==-1)
{
throw new InvalidOperationException ();
}
if (_position >= _student.Length)
{
throw new InvalidOperationException();
}
return _student[_position];
}
}
public bool MoveNext()//就是让我们把操作推进到下一个
{
if (_position<_student.Length-1)
{
_position++;
return true;
}
else
{
return false;
}
}
public void Reset()//重置
{
_position = -1;
}
}
}
如若不理解,思考list集合的遍历;