学习地址:https://www.cnblogs.com/leemano/p/4908505.html
实战代码讲解:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
public class Example
{
class Student
{
public int id;
public string name;
}
//从IEnumerable继承
class StudentCollection : IEnumerable
{
public List<Student> students = new List<Student>();
public void Add(Student student)
{
students.Add(student);
}
public IEnumerator GetEnumerator()
{
foreach (var s in students)
{
yield return s;
//继续执行在这个位置
Console.WriteLine("test");
}
}
}
public static void Main()
{
StudentCollection mc = new StudentCollection();
mc.Add(new Student {id = 0 });
mc.Add(new Student {id = 1 });
mc.Add(new Student() {id = 2 });
//下面调试可以GetEnumerator里调试流程
foreach (Student student in mc)
{
var id = student.id;
}
// Keep the console window open in debug mode
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}