C#中foreach遍历学习笔记
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ForeachDemo { class Program { static void Main() { Mylist list = new Mylist(); MyList2 list2 = new MyList2(); foreach (string str in list) { Console.WriteLine(str); } Console.WriteLine("=========================================="); foreach (string str in list2) { Console.WriteLine(str); } } } class Mylist : IEnumerable //通过yield return 来返回,实现IEnumerable接口 { static string[] testString= { "0", "2", "4", "6" ,"8"}; public IEnumerator GetEnumerator() { foreach (string str in testString) { yield return str; } } } class MyList2 : IEnumerable //实现自己的IEnumerator来实现 { static string[] testString2 = { "1", "3", "5", "7", "9" }; public IEnumerator GetEnumerator() { return new MyEnumerator(); } private class MyEnumerator : IEnumerator { int index = -1; public object Current { get { return testString2[index]; } } public bool MoveNext() { if (++index >= testString2.Length) { return false; } else { return true; } } public void Reset() { index = -1; } } } }
参考:
http://www.cnblogs.com/jesse2013/p/CollectionsInCSharp.html
http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html
本博客文章皆出于学习目的,个人总结或摘抄整理自网络。引用参考部分在文章中都有原文链接,如疏忽未给出请联系本人。另外,作为一名菜鸟程序媛,如文章内容有错误,欢迎点击博客右上方的扣扣链接指导交流。