C#实现IEnumerator与IEnumerable完成foreach遍历

实现IEnumerator与IEnumerable完成foreach遍历

重写IEnumerator

public class ColorEnumerator : IEnumerator
    {
        string[] colors;

        int position = -1;

        /// <summary>
        /// 实现构造函数
        /// </summary>
        /// <param name="theColors"></param>
        public ColorEnumerator(string[] theColors)
        {
            colors = new string[theColors.Length];
            for (int i = 0; i < theColors.Length; i++)
            {
                colors[i] = theColors[i];
            }
        }

        /// <summary>
        /// 实现当前索引
        /// </summary>
        public object Current
        {
            get
            {
                if (position == -1)
                {
                    throw new InvalidOperationException();
                }
                if (position >= colors.Length)
                {
                    throw new InvalidOperationException();
                }

                return colors[position];
            }
        }

        /// <summary>
        /// 实现索引指向
        /// </summary>
        /// <returns></returns>
        public bool MoveNext()
        {
            if (position < colors.Length - 1)
            {
                position++;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 重制索引
        /// </summary>
        public void Reset()
        {
            position = -1;
        }
    }

重写IEnumerable

  public class Spectrum : IEnumerable
    {
        string[] colors = { "violet", "blue", "cyan", "green", "yellow", "orange", "red"}; 
        public IEnumerator GetEnumerator()
        {
            Console.WriteLine("调用了");
            return new ColorEnumerator(colors);
        }
    }

我们来看一下调用

 Spectrum spectrum = new Spectrum();
  foreach (string color in spectrum)
 {
        Console.WriteLine(color);
 }

再来看一下运行结果

 

 

 在foreach中会调用spectrum.GetEnumerator()方法

posted @ 2021-06-30 11:38  zjp971014  阅读(343)  评论(0)    收藏  举报