代码实现:
首先创建用来遍历的类
class Car { public string name; public int age; } public class Cars: IEnumerable { Car[] acrArr = new Car[4]; public Cars() { acrArr[0] = new Car() { name = "1", age = 10 }; acrArr[1] = new Car() { name = "2", age = 20 }; acrArr[2] = new Car() { name = "3", age = 30 }; acrArr[3] = new Car() { name = "4", age = 40 }; } public IEnumerator GetEnumerator() { return this.acrArr.GetEnumerator(); } }
然后直接调用foreach
foreach (Car ccc in new Cars()) { console.writeLine(ccc.age.ToString() + "\r\n"); }
参考文章:
标签:name,C#,Car,age,acrArr,foreach,类型,new,public From: https://www.cnblogs.com/Kirito-Asuna-Yoyi/p/class_using_foreach.html