在不使用'yield return'的情况下实现IEnumerator

Gir*_*iri 0 c# ienumerable ienumerator yield-return

我正在学习C#中的迭代器概念,并且正在试验代码,采用简单的问题并尝试以不同的方式实现.我试图在列表中显示所有术语,因为我正在尝试不同的方法来获得结果.在下面的代码中,我使用了两个类ListIterator和ImplementList.

在ListIterator类中:我定义了一个HashSet,它使用IEnumerator来存储值.这里GetEnumerator()方法返回列表中的值.GetEnumerator在ImplementList类(其他类)中实现.最后,列表显示在控制台中.

public class ListIterator
{ 
   public void DisplayList()
   {
    HashSet<int> myhashSet = new HashSet<int> { 30, 4, 27, 35, 96, 34};
    IEnumerator<int> IE = myhashSet.GetEnumerator();
    while (IE.MoveNext())
      {
        int x = IE.Current;
        Console.Write("{0} ", x);
      }
      Console.WriteLine();
    Console.ReadKey();
   }
}
Run Code Online (Sandbox Code Playgroud)

在ImplementList类中:定义了GetEnumerator(),它使用yield return x返回列表.

public class ImplementList : IList<int>
  {
    private List<int> Mylist = new List<int>();
    public ImplementList() { }

    public void Add(int item) 
    { 
        Mylist.Add(item); 
    }

    public IEnumerator<int> GetEnumerator()
    {
      foreach (int x in Mylist)
        yield return x;
    }
  }
Run Code Online (Sandbox Code Playgroud)

现在,我想重写GetEnumerator()而不使用yield return.它应该返回列表中的所有值.是否可以在IEnumerator中使用yield return而获取列表中的所有值

Liv*_* M. 5

您可以使用内部列表的Enumerator实现MyList:

    public IEnumerator<int> GetEnumerator()
    {
      return MyList.GetEnumerator();
    }
Run Code Online (Sandbox Code Playgroud)

或者您可以自己实现IEnumerator(来自MSDN):

public class People : IEnumerable
{
    private Person[] _people;
    public People(Person[] pArray)
    {
        _people = new Person[pArray.Length];

        for (int i = 0; i < pArray.Length; i++)
        {
            _people[i] = pArray[i];
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
       return (IEnumerator) GetEnumerator();
    }

    public PeopleEnum GetEnumerator()
    {
        return new PeopleEnum(_people);
    }
}

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;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

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