国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#類可以通過foreach遍歷的原理

2019-11-17 02:17:52
字體:
來源:轉載
供稿:網友
C#類可以通過foreach遍歷的原理

要使用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:IEnumerable26     {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             set36             {37                 if (index>=Count)38                 {39                     listStudent.Add(value);40                 }41                 else42                 {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:IEnumerator57     {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 Current67         {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             else79             {80                 return true;81             }82         }83 84         public void Reset()85         {86             index = -1;87         }88     }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沁源县| 青海省| 鱼台县| 夏津县| 进贤县| 灌云县| 扶绥县| 伊宁市| 仪征市| 名山县| 贵阳市| 菏泽市| 依安县| 涟水县| 翁牛特旗| 肇源县| 北海市| 通榆县| 曲周县| 新郑市| 留坝县| 绥化市| 丹阳市| 延津县| 绵阳市| 饶阳县| 来安县| 获嘉县| 通辽市| 陵水| 大宁县| 开化县| 榆中县| 蓬溪县| 呼和浩特市| 呼玛县| 左权县| 阿巴嘎旗| 平山县| 永清县| 鄂托克前旗|