C# 非泛型集合的简单迭代
IEnumerator接口:支持对非泛型集合的简单迭代,使得foreach可以遍寻集合
using System; using System.Collections;
public class Family { private string husban = null; public string Husban { get { return husban; } set { husban = value; } } private string wife = null; public string Wife { get { return wife; } set { this.wife = value; } } private string son = null; public string Son { get { return this.son; } set { this.son = value; } } private string daughter = null; public string Daughter { get { return this.daughter; } set { this.daughter = value; } } public Family(string husban, string wife, string daughter, string son) { this.husban = husban; this.wife = wife; this.daughter = daughter; this.son = son; } } public class Families : IEnumerable { Family[] families; public Families(Family[] familyList) { this.families = new Family[familyList.Length]; for (int i = 0; i < familyList.Length; i++) this.families[i] = familyList[i]; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)this.GetEnumerator(); } FamilyEnumerator GetEnumerator() { return new FamilyEnumerator(this.families); } } public class FamilyEnumerator : IEnumerator { public Family[] families; int index = -1; public FamilyEnumerator(Family[] familyList) { this.families = familyList; } /// <summary> /// 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前 /// </summary> public void Reset() { index = -1; } /// <summary> /// 获取集合中位于枚举数当前位置的元素 /// </summary> public Family Current { get { try { return this.families[index]; } catch (IndexOutOfRangeException e) { throw new InvalidOperationException(); } } } /// <summary> /// 将枚举数推进到集合的下一个元素 /// </summary> /// <returns></returns> public bool MoveNext() { index++; return index < this.families.Length; } object IEnumerator.Current { get { return Current; } } }
static void Main(string[] args) { Family[] familyList = new Family[] { new Family("echo","zp","cc","ef"), new Family("zhubaba","zhumama","peiqi","qiaozhi"), }; Families families = new Families(familyList); foreach (Family fam in families) { Console.WriteLine($"{fam.Husban} {fam.Wife} {fam.Son} {fam.Daughter}"); } }
 
------------------------------------
承接
**视觉检测软件开发及调试
**工业软件开发
**上位机软件开发
wechat:luoran2024
qq:565934058
email:taoyuansu@qq.com
海量教育资源及影视资源下载
微信公众号:EFun科技
------------------------------------
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号