Foreach原理

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Collections;
 6 
 7 namespace _15Foreach原理
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Person p = new Person();
14             p[0] = "奇瑞QQ";
15             p[1] = "infiniti";
16             p[2] = "阿斯顿马丁";
17             foreach (string item in p)
18             {
19                 Console.WriteLine(item);
20             }
21             //内部实现
22             //IEnumerator etor = p.GetEnumerator();
23             //while (etor.MoveNext())
24             //{
25             //    string str = etor.Current.ToString();
26             //    Console.WriteLine(str);
27             //}
28             Console.ReadKey();
29         }
30     }
31     public class Person : IEnumerable
32     {
33         private List<string> listCar = new List<string>();
34         public int Count
35         {
36             get { return this.listCar.Count; }
37         }
38         public string this[int index]
39         {
40             get { return listCar[index]; }
41             set { if (index >= listCar.Count) { listCar.Add(value); } else { listCar[index] = value; } }
42         }
43         public string Name { get; set; }
44         public int Age { get; set; }
45         public string Email { get; set; }
46         //这个方法的作用不是用来遍历的,而是用来获取一个对象
47         //这个对象才是用来遍历的。
48         public IEnumerator GetEnumerator()
49         {
50             return new PersonEnumerator(listCar);
51         }
52     }
53     //这个类型,的作用就是用来遍历Person中的List集合的。
54     public class PersonEnumerator : IEnumerator
55     {
56         public PersonEnumerator(List<string> _cars)
57         {
58             cars = _cars;
59         }
60         //这个字段中存储的就是Person对象中的listCar集合
61         private List<string> cars;
62         //假设一开始遍历的对象的索引是-1
63         private int index = -1;
64         //表示获取当前正在遍历的那个对象
65         public object Current { get { if (index < 0) { return null; } return cars[index]; } }
66         //让自定义下标index累加
67         public bool MoveNext()
68         {
69             index = index + 1;
70             if (index >= cars.Count) { return false; } else { return true; }
71         }
72         public void Reset() { index = -1; }
73     }
74 }
原文地址:https://www.cnblogs.com/cheshui/p/2701998.html