1. 程式人生 > 其它 >IEnumerable<T>的應用

IEnumerable<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); } }
程式設計是個人愛好