实现 IEnumerator IEnumerable

本文介绍如何在C#中使用IEnumerator接口和IEnumerable接口实现颜色枚举和迭代器,通过创建自定义枚举类Mycolrs来演示颜色的遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication46
{
    class Program
    {
        // IEnumerator  接口里面有三个函数成员 : Current ,MoveNext,Rest ; MoveNext 必须在第一次使用Current之前使用
        // IEnumerable   接口里面只有一个成员  GetEnumerator 方法 返回的事 对象的枚举数 -- IEnumerator 

        static void Main(string[] args)
        {

            int[] a = new int[] { 1, 2, 5, 7 };
            foreach (var item in a)
            {
                Console.WriteLine(item);
            }
            Mycolrs mc = new Mycolrs();


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


    class ColorEnumerator : IEnumerator
    {

        int Position = -1;
        string[] Colors;
        public object Current
        {


            get
            {

                if (Position == -1)
                {

                    throw new InvalidOperationException();
                }
                if (Position == Colors.Length)
                {
                    throw new InvalidOperationException();
                }
                return Colors[Position];
            }
        }

        public bool MoveNext()
        {
            if (Position < Colors.Length - 1)
            {
                Position++;
                return true;

            }
            else
            {
                return false;
            }


        }

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

        public ColorEnumerator(string[] theColors)
        {
            Colors = new string[theColors.Length];
            for (int i = 0; i < Colors.Length; i++)
            {

                Colors[i] = theColors[i];
            }


        }
    }


   class Mycolrs:IEnumerable
   {
       string[] Colors = { "red", "Yellow", "Blue" };

       public IEnumerator GetEnumerator()
       {
          return  new ColorEnumerator(Colors);
       }
   }

}

 

转载于:https://www.cnblogs.com/xh0626/p/4842573.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值