脚本宝典收集整理的这篇文章主要介绍了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); } }
以上是脚本宝典为你收集整理的IEnumerable<T>的应用全部内容,希望文章能够帮你解决IEnumerable<T>的应用所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。