自己建立的类中,可以通过迭代器列出所有的成员
需用到 IEnumerable
建立 Students 类,通过迭代列出所有的student的id和name
class Student { public int Id { get; set; } public string Name { get; set; } } class Students :IEnumerable { public List<Student> students = new List<Student>(); public void Add(int id,string name) => students.Add(new Student { Id=id,Name=name}); public IEnumerator GetEnumerator() { foreach (var s in students) { yield return s; } } }
新建一个按钮和文本框,写入代码
private void button1_Click(object sender, EventArgs e) { Students st = new Students(); st.Add(0, "Tony"); st.Add(1, "Micheal"); st.Add(2, "Amy"); foreach (var s in st) { Student st1 = (Student)s;
textBox1.AppendText(st1.Id.ToString() +":"+ st1.Name+"\r\n");
} }
标签:迭代,C#,st,Students,Add,foreach,Student,public From: https://www.cnblogs.com/hiyanhao/p/16995562.html