zoukankan      html  css  js  c++  java
  • IEnumerable 和 IEnumerator 接口的作用

    实现IEnumerable接口的类,可以支持foreach循环遍历对象的集合元素

    IEnumerable:
    IEnumerator GetEnumerator() 返回可循环访问集合的枚举数。

    IEnumerator:
    object Current 获取集合中的当前元素。
    bool MoveNext() 将枚举数推进到集合的下一个元素。
    如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false
    void Reset() 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。


    sample:
    using System;
    using System.Collections;

    namespace ConsoleApplication1
    {
        
    /// <summary>
        
    /// Summary description for Class1.
        
    /// </summary>

        class Class1
        
    {
            
    /// <summary>
            
    /// The main entry point for the application.
            
    /// </summary>

            [STAThread]
            
    static void Main(string[] args)
            
    {
                CStringEnum se 
    = new CStringEnum();

                
    foreach (string s in se)
                
    {
                    Console.WriteLine(s);
                }


                Console.Read() ;
            }

        }


        
    class CStringEnum : IEnumerable, IEnumerator
        
    {
            
    string[] items = new string[16];
            
    int index = -1;

            
    public CStringEnum()
            
    {
                
    for(int i=0; i<items.Length; ++i)
                    items[i] 
    = "s" + i.ToString();
            }


            
    #region IEnumerable Members

            
    public IEnumerator GetEnumerator()
            
    {
                
    // TODO:  Add StringCollection.GetEnumerator implementation
                return (IEnumerator)this;
            }


            
    #endregion


            
    #region IEnumerator Members

            
    public void Reset()
            
    {
                
    // TODO:  Add CStringEnum.Reset implementation
                index = -1;
            }


            
    public object Current
            
    {
                
    get
                
    {
                    
    // TODO:  Add CStringEnum.Current getter implementation
                    return items[index];
                }

            }


            
    public bool MoveNext()
            
    {
                
    // TODO:  Add CStringEnum.MoveNext implementation
                index++;
                
    return index >= items.Length ? false : true;
            }


            
    #endregion

        }


    }

    转自:http://www.cnblogs.com/netflu/archive/2006/07/31/463974.html

    收藏起来,便于温习

  • 相关阅读:
    Effective STL~2 vector和string(条款13~18)
    Effective STL~5 算法
    Effective STL~6 函数子、函数子类、函数及其他
    Effective STL~7 在程序中使用STL
    Effective STL~4 迭代器(条款26~29)
    STL std::remove和std::remove_if
    C/C++ 计算算法的执行时间
    Effective STL~3 关联容器(条款19~25)
    Effective C++读书笔记~7 模板与泛型编程
    C++ Primer学习笔记 原始内存分配类allocator
  • 原文地址:https://www.cnblogs.com/xiaopin/p/1930535.html
Copyright © 2011-2022 走看看