星空网 > 软件开发 > ASP.net

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   }

 




原标题:C#类可以通过foreach遍历的原理

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

J&T Express_快递公司:https://www.ikjzd.com/w/1773
云路供应链_一体化方案:https://www.ikjzd.com/w/1774
杨顺龙_wish讲师:https://www.ikjzd.com/w/1775
邮乐网:https://www.ikjzd.com/w/1776
刘曦_wish讲师:https://www.ikjzd.com/w/1777
SPUTNIK:https://www.ikjzd.com/w/1778
探讨内地人开设香港账户的可行性 :https://www.kjdsnews.com/a/1836442.html
在古巴做游轮 古巴旅游项目:https://www.vstour.cn/a/363194.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流