C# - 为什么在实现IEnumberable接口时实现两个版本的Current?

q09*_*987 5 c#

我假设以下示例提供了在实现IEnumberable接口时应遵循的最佳实践.

http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.movenext.aspx

这是一个问题:

  1. 我们为什么要提供两种版本的Current方法?
  2. 当使用版本ONE(对象IEnumerator.Current)?
  3. 当使用版本TWO(公共人员当前)?
  4. 如何在foreach语句中使用PeopleEnum.// 更新

谢谢

public class PeopleEnum : IEnumerator
{
    public Person[] _people;

    // Enumerators are positioned before the first element
    // until the first MoveNext() call.
    int position = -1;

    public PeopleEnum(Person[] list)
    {
        _people = list;
    }

    public bool MoveNext()
    {
        position++;
        return (position < _people.Length);
    }

    public void Reset()
    {
        position = -1;
    }

    // explicit interface implementation
    object IEnumerator.Current /// **version ONE**
    {
        get
        {
            return Current;
        }
    }

    public Person Current     /// **version TWO**
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 7

IEnumerator.Current是一个显式的接口实现.

只有将迭代器强制转换为IEnumerator(这是框架所做的foreach),才能使用它.在其他情况下,将使用第二个版本.

您将看到它返回object并实际使用返回a的其他实现Person.

接口本身不需要第二个实现,但是为方便起见而且为了返回预期的类型而不是object.


Bro*_*ass 2

我怀疑原因是此代码示例派生自示例类实现IEnumerator<T>- 如果示例类PeopleEnum实现了IEnumerator<T>此方法,则需要: IEnumerator<T>继承 IEnumerator,因此在实现时必须实现两个接口 IEnumerator<T>

非泛型的实现IEnumerator 需要返回对象 -另一方面,Current强类型 要求 Current 返回类型的实例- 使用显式和直接的接口实现是满足这两个要求的唯一方法。IEnumerator<T>T