zoukankan      html  css  js  c++  java
  • 实现 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);
           }
       }
    
    }
    
  • 相关阅读:
    sqlachemy查询对象转化成字典/json使用
    pandas DF去重
    flask request和response
    flask路由要点
    flask项目结构
    __init__.py在导包中起到的作用
    git 查看修改账号密码
    02.flask-script
    vue点击父组件里面的列表动态传值到子组件
    安卓手机点击背景图会出现预览的情况
  • 原文地址:https://www.cnblogs.com/xh0626/p/4842573.html
Copyright © 2011-2022 走看看