C#????????foreach?????????
???????????? ???????[ 2015/6/29 11:16:54 ] ???????????????
????????foreach???????????????????????
????1??????????????? public IEnumerator GetEnumerator(){}??????????IEnumerable???????????????
????2????????? public IEnumerator GetEnumerator(){}?У??????????????????????????????????????IEnumerator ???
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Person p = new Person();
6 p[0] = "С??";
7 p[1] = "????";
8 p[2] = "С??";
9 p[3] = "С??";
10 for (int i = 0; i < p.Count; i++)
11 {
12 Console.WriteLine(p[i]);
13 }
14 15 Console.WriteLine("==========================================");
17 foreach (var name in p)
18 {
19 Console.WriteLine(name);
20 }
21 Console.ReadKey();
22 }
23 }
24
25 internal class Person:IEnumerable
26 {
27 private List<string> listStudent =new List<string>();
28 public int Count {
29 get { return listStudent.Count; }
30 }
31
32 public string this[int index]
33 {
34 get { return listStudent[index]; }
35 set
36 {
37 if (index>=Count)
38 {
39 listStudent.Add(value);
40 }
41 else
42 {
43 listStudent[index] = value;
44 }
45 }
46 }
47
48
49
50 public IEnumerator GetEnumerator()
51 {
52 return new PersonIEnumerator(listStudent);
53 }
54 }
55
56 class PersonIEnumerator:IEnumerator
57 {
58 public PersonIEnumerator(List<string> _listName)
59 {
60 listName = _listName;
61 }
62
63 private List<string> listName;
64 private int index = -1;
65
66 public object Current
67 {
68 get {return listName[index]; }
69 }
70
71 public bool MoveNext()
72 {
73 index++;
74 if (index>=listName.Count)
75 {
76 return false;
77 }
78 else
79 {
80 return true;
81 }
82 }
83
84 public void Reset()
85 {
86 index = -1;
87 }
88 }
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11