1.创建实体Student
public class Student : IEnumerable<Student>
{
public static List<Student> stus = new List<Student>();
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime CreateTime { get; set; }
public IEnumerable<Student> this[int index]
{
get
{
yield return stus[index];
}
}
public void AddStudent(Student stu)
{
stus.Add(stu);
}
public IEnumerator<Student> GetEnumerator()
{
foreach (var item in stus)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return stus.GetEnumerator();
}
}
调用:
Student stu = new Student();
stu.AddStudent(new Student { Age = 25, Id = 1, Name = "czj1" });
stu.AddStudent(new Student { Age = 25, Id = 2, Name = "czj2" });
stu.AddStudent(new Student { Age = 25, Id = 3, Name = "czj3" });
var stu0 = stu[0];
foreach (var item in stu0)
{
Console.WriteLine($"Id:{item.Id},Name:{item.Name}");
}
//遍历Student类中的集合
foreach (Student item in stu)
{
Console.WriteLine($"Id:{item.Id},Name:{item.Name}");
}
输出==》
2.直接在方法中使用
public static IEnumerable<Student> GetList()
{
List<Student> stus = new List<Student>();
stus.Add(new Student { Age = 25, Id = 1, Name = "czj1" });
stus.Add(new Student { Age = 25, Id = 2, Name = "czj2" });
stus.Add(new Student { Age = 25, Id = 3, Name = "czj3" });
foreach (var item in stus)
{
yield return item;
}
}
调用:
static void Main(string[] args)
{
foreach (var item in GetList())
{
Console.WriteLine($"Id:{item.Id},Name:{item.Name}");
}
}
输出==》