C# 迭代器
IEnumerable 和 IEnumerator 的 泛型版本是新式代码的首要选项。IEnumerable<T> 和 IEnumerator<T>
IEnumerable<T>的应用
写两个类一个是学生、一个是班级。逻辑上学生是属于班级这个集合的,按理来说是可以直接使用foreach直接遍历出班级里面的学生。但是由于ClassOfStudent未实现 IEnumerable或IEnumerable<T>接口
出现编译报错:“ClassOfStudent”不包含“GetEnumerator”的公共实例或扩展定义,因此 foreach 语句不能作用于“ClassOfStudent”类型的变量
public class Test { static void Main(string[] args) { Student[] st = new Student[2]; ClassOfStudent ClassTwoOfTheThirdYear = new ClassOfStudent(); ClassTwoOfTheThirdYear.AddStudent(new Student { Name = "xsdfsdf", Age = 12 }); ClassTwoOfTheThirdYear.AddStudent(new Student { Name = "xsdff", Age = 12 }); //ClassOfStudent未实现 IEnumerable或IEnumerable<T>接口时候编译器报错: //“ClassOfStudent”不包含“GetEnumerator”的公共实例或扩展定义,因此 foreach 语句不能作用于“ClassOfStudent”类型的变量 foreach (var stu in ClassTwoOfTheThirdYear) { Console.WriteLine(stu.Name); } } } public class Student : IComparable<Student> { private string name; private int age; private int dage; public string Name { get => name; set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("不能使用空白名称", "Name"); name = value; } } public int Age { get => age; set => age = value; } public int Dage { get => dage; set => dage = value; } public string this[string name] { get => name; set { name = value; } } //重载比较方法 public int CompareTo(Student st) { return this.name.CompareTo(st.name); } //重载 ToString()方法 public override string ToString() { return string.Format($"姓名:{this.name} 年龄:{this.age}"); } //重载操作符 + public static Student operator +(Student st, Student st1) { return new Student { Name = st.name + st1.name, Age = st.age + st1.age }; } public static implicit operator Student(int st) { return new Student { Name = "", Age = st }; } public static explicit operator int(Student st) { return st.Age; } } public class ClassOfStudent { private string className; private int studentNumber; private List<Student> students; public string ClassName { get => className; set => className = value; } public int StudentNumber { get => studentNumber; set => studentNumber = value; } public void AddStudent(Student st) { students.Add(st); } }
编程是个人爱好