只要在类里实现IEnumerable接口,就可以对类的实例化进行枚举操作。
internal class Program
{
static void Main(string[] args)
{
Student student = new Student { Id=1 };
foreach(string i in student)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}
internal class Student : IEnumerable
{
private int _id;
public int Id { get => _id; set => _id = value; }
public IEnumerator GetEnumerator() //枚举接口的实现
{
yield return "Ant1编程";
yield return "Ant2编程";
yield return "Ant3编程";
yield return "Ant4编程";
}
}