《C#入门到精通》学习笔记 -- IEnumerable和IEnumberator接口

http://www.cnblogs.com/wxwx110/archive/2007/02/26/657090.html

C# defines two interfaces to enumerate a collective object. Now let us see them:
public interface IEnumerator
{       
    object Current { get; }
    bool MoveNext();
    void Reset();
}
public interface IEnumerable
{
   IEnumerator GetEnumerator();
}
Now the question is: why does need the two interface? Maybe IEnumerator is enough. The Example is below::
class MyData : IEnumerator
{
   private int[] data;
   private int index;
       
   public MyData()
   {
       data = new int[10];
       index = -1;
    }
    public object Current
    {
        get { return data[index]; }
    }
    public bool MoveNext()
    {
        return ++index < data.Length;
    }
    public void  Reset()
    {
        index = -1;
    }
}

Is there any problem with this?
 Yes, there is. If you implement IEnumerator interface, not IEnumerable, there will be subtle problematic in some special cases. Now begin another example with MyData class object: 
IEnumerator e = new MyData();
while (e.MoveNext())
{
  object o = e.Current;
  {
e.MoveNext();
    object o2 = e.Current;
    DoSomethingWith(o,o2);
   }
 }
 Do you see the potential problem above? This is caused by the essence of the IEnumberator interface. This interface force us to use the enumerator in this way:

 Set the original iterative position before the starting (Reset)
 Call MoveNext() function to move the position to the next, and check the current element is existing 
 Get the current element from the Property Current
So , the IEnumberator is often implemented by using some internal state( in our MyData example it is the class instance member index). When you use the IEnumberator variable, you have to use it in the special way illuminated above. But when you use it in a nested way, you maybe destroy the object internal state, and the behavior is undefined. 
 So, the .NET Framework provide another interface IEnumberable, which creates an IEnumerator variable by a function GetEnumberator(), and the internal state is saved in the variable returned. When you use it, you change the variable internal state, not the class instance variable implementing the interface IEnumerable, and the undefined behavior will never happen again. 
 And remember, foreach is for IEnumerable, not for IEnumberator.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值