zoukankan      html  css  js  c++  java
  • c#中 IEnumerable与IEnumerator接口

     

    【转载】IEnumerable与IEnumerator在C#中的应用

    http://blog.csdn.net/qq546937127/archive/2010/03/12/5372205.aspx

    msdn:http://msdn.microsoft.com/zh-cn/library/system.collections.ienumerator(VS.80).aspx#Y100

    1. IEnumerable接口表示该类的对象是可以枚举的,强调了它的能力。它定义了一个GetEnumerator();的方法,该方法返回IEnumerator接口,即枚举器对象

     1 public interface IEnumerable
    2 {
    3 // 摘要:
    4 // Returns an enumerator that iterates through a collection.
    5 //
    6 // 返回结果:
    7 // An System.Collections.IEnumerator object that can be used to iterate through
    8 // the collection.
    9 [DispId(-4)]
    10 IEnumerator GetEnumerator();
    11 }

    2. IEnumerator接口是一个枚举器。

     1 public interface IEnumerator
    2 {
    3 // 摘要:
    4 // Gets the current element in the collection.
    5 //
    6 // 返回结果:
    7 // The current element in the collection.
    8 //
    9 // 异常:
    10 // System.InvalidOperationException:
    11 // The enumerator is positioned before the first element of the collection or
    12 // after the last element.
    13 object Current { get; }
    14
    15 // 摘要:
    16 // Advances the enumerator to the next element of the collection.
    17 //
    18 // 返回结果:
    19 // true if the enumerator was successfully advanced to the next element; false
    20 // if the enumerator has passed the end of the collection.
    21 //
    22 // 异常:
    23 // System.InvalidOperationException:
    24 // The collection was modified after the enumerator was created.
    25 bool MoveNext();
    26 //
    27 // 摘要:
    28 // Sets the enumerator to its initial position, which is before the first element
    29 // in the collection.
    30 //
    31 // 异常:
    32 // System.InvalidOperationException:
    33 // The collection was modified after the enumerator was created.
    34 void Reset();
    35 }

    注:通过实验发现,只要类存在IEnumerator GetEnumerator();方法,但不实现 IEnumerable接口,也是可以foreach的,可能是foreach的实现机制中没有强烈要求一定实现IEnumerable接口。暂时不知道这样做的原因是什么。

    总结:c#中的foreach 可以循环遍历一个IEnumerable对象。

  • 相关阅读:
    beta冲刺总结
    beta冲刺第六天
    beta冲刺第四天
    beta冲刺第五天
    beta冲刺第三天
    beta冲刺第一天
    beta冲刺第二天
    beta冲刺前的准备
    【转载】Android 装载器---使用LoaderManager的回调方法
    【转载】Android之用PopupWindow实现弹出菜单
  • 原文地址:https://www.cnblogs.com/skysoft001/p/1972379.html
Copyright © 2011-2022 走看看