zoukankan      html  css  js  c++  java
  • IEnumerable IEnumerator 支持foreach

    代码无实际意义, 贴上代码备忘:

     1using System;
     2using System.Collections.Generic;
     3using System.Text;
     4using System.Collections;
     5
     6namespace ImpEnumeratable
     7{
     8    class Collec : IEnumerable
     9    {
    10        public List<Itor> Items = new List<Itor>();
    11       
    12
    13        IEnumerable 成员
    21
    22        public void Add(Itor it)
    23        {
    24            Items.Add(it);            
    25        }

    26    }

    27
    28    class Itor : IEnumerator
    29    {
    30        public string N;
    31
    32        int posotion = -1;
    33        Collec c;
    34
    35        public Itor(Collec cc)
    36        {
    37            c = cc;
    38            posotion = -1;
    39        }

    40
    41        public Itor(string s)
    42        {
    43            N = s;
    44        }

    45
    46        IEnumerator 成员
    75    }

    76
    77
    78    class Program
    79    {
    80        static void Main(string[] args)
    81        {
    82            Collec cols = new Collec();
    83
    84            Itor it01 = new Itor("Hello ");
    85            Itor it02 = new Itor("World");
    86
    87            cols.Add(it01);
    88            cols.Add(it02);
    89                       
    90            foreach (Itor i in cols)
    91            {
    92                Console.WriteLine(i.N);
    93            }

    94        }

    95    }

    96}

    97

    一般将Itor类放入Collec 内部声明, 集合和集合中的元素紧耦合。 还可保证类型安全。

     可以实现范型接口  public interface IEnumerator<T> : IDisposable, IEnumerator  
                              public interface IEnumerable<T> : IEnumerable
    来实现范型版本。

  • 相关阅读:
    【cdq分治】【P4390】[BOI2007]Mokia 摩基亚
    【树上莫队】【SP10707】 COT2
    【费用流】【网络流24题】【P1251】 餐巾计划问题
    【费用流】【网络流24题】【P4014】 分配问题
    【MST】P2323 [HNOI2006]公路修建问题
    【组合数学】【P5216】DLS采花
    【线段树】【P4198】 楼房重建
    【整体二分】【P3527】 [POI2011]MET-Meteors
    【线性基/神仙题】P4151 [WC2011]最大XOR和路径
    【枚举&数据结构】【P2484】 [SDOI2011]打地鼠
  • 原文地址:https://www.cnblogs.com/yizhinantian/p/921951.html
Copyright © 2011-2022 走看看