• 实现 IEnumerator IEnumerable


    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);
           }
       }
    
    }
    
  • 相关阅读:
    8.8全民健身日,扒一扒音视频互动与健身的那些事儿
    游戏视频开发平台的特点
    音视频开发技术之自主集成第三方编解码器
    视频开发之外部音视频输入
    视频开发技术之文件传输限速
    视频开发技术之文件传输
    ubuntu16.04LTS+pycharm kuaijiefangshi
    install cuda
    Tensorflow实现MNIST
    TensorFlow导入mnist数据集
  • 原文地址:https://www.cnblogs.com/xh0626/p/4842573.html
Copyright © 2020-2023  润新知