首页 > 技术文章 > C#中foreach遍历学习笔记

goingforward 2015-11-13 14:27 原文

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

推荐阅读