用foreach遍历访问的对象需要实现 IEnumerable  接口或声明 GetEnumerator 方法的类型。

先来看看IEnumerable接口:
namespace System.Collections
{
    // Summary:
    //     Exposes the enumerator, which supports a simple iteration over a non-generic
    //     collection.
    [ComVisible(true)]
    [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
    public interface IEnumerable
    {
        // Summary:
        //     Returns an enumerator that iterates through a collection.
        //
        // Returns:
        //     An System.Collections.IEnumerator object that can be used to iterate through
        //     the collection.
        [DispId(-4)]
        IEnumerator GetEnumerator();
    }
}

IEnumerator接口:

namespace System.Collections
{
    // Summary:
    //     Supports a simple iteration over a nongeneric collection.
     [ComVisible(true)]
     [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
     public interface IEnumerator
    {

         object Current { get; }
 
         bool MoveNext();

         void Reset();
     }
 }

示例:

namespace ForeachDemo
{
    public class MySplit : IEnumerable
    {
        private string[] elements;

        public MySplit(string source,char[] delimiters)
        {
            elements = source.Split(delimiters);
        }

        public string[] Elements
        {
            get
            {
                return elements;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new MyEnumerator(this);
        }
    }

    public class MyEnumerator : IEnumerator
    {
        private int position = -1;
        private MySplit t;

        public MyEnumerator(MySplit t)
        {
            this.t = t;
        }

        public bool MoveNext()
        {
           if (position<t.Elements.Length - 1)
           {
               position++;
               return true;
           }
           else
           {
               return false;
           }
        }

        public void Reset()
        {
            position = -1;
        }

        object IEnumerator.Current
        {
            get
            {
                try
                {
                    return t.Elements[position];
                }
                catch(IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MySplit mysplit = new MySplit("i am a good student.",new char[]{' '});

            foreach(string item in mysplit)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
    }
}

输出:

 
posted on 2013-10-29 11:01  zzunstu  阅读(2117)  评论(0编辑  收藏  举报