IEnumerable IEnumerator 支持foreach

代码无实际意义, 贴上代码备忘:

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4using System.Collections;
 5
 6namespace ImpEnumeratable
 7{
 8    class Collec : IEnumerable
 9    {
10        public List<Itor> Items = new List<Itor>();
11       
12
13        IEnumerable 成员
21
22        public void Add(Itor it)
23        {
24            Items.Add(it);            
25        }

26    }

27
28    class Itor : IEnumerator
29    {
30        public string N;
31
32        int posotion = -1;
33        Collec c;
34
35        public Itor(Collec cc)
36        {
37            c = cc;
38            posotion = -1;
39        }

40
41        public Itor(string s)
42        {
43            N = s;
44        }

45
46        IEnumerator 成员
75    }

76
77
78    class Program
79    {
80        static void Main(string[] args)
81        {
82            Collec cols = new Collec();
83
84            Itor it01 = new Itor("Hello ");
85            Itor it02 = new Itor("World");
86
87            cols.Add(it01);
88            cols.Add(it02);
89                       
90            foreach (Itor i in cols)
91            {
92                Console.WriteLine(i.N);
93            }

94        }

95    }

96}

97

一般将Itor类放入Collec 内部声明, 集合和集合中的元素紧耦合。 还可保证类型安全。

 可以实现范型接口  public interface IEnumerator<T> : IDisposable, IEnumerator  
                          public interface IEnumerable<T> : IEnumerable
来实现范型版本。

原文地址:https://www.cnblogs.com/yizhinantian/p/921951.html