不使用'yield return'的IEnumerator实现

本文关键字:IEnumerator 实现 return yield | 更新日期: 2023-09-27 18:14:08

我正在学习c#中的迭代器概念,并且正在试验代码,采取简单的问题并尝试以不同的方式实现。我试图在一个列表中显示所有的项,为此我尝试了不同的方法来获得结果。在下面的代码中,我使用了两个类listtiterator和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();
   }
}

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

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

不使用'yield return'的IEnumerator实现

中的yield return

您可以使用枚举器实现您的内部列表MyList:

    public IEnumerator<int> GetEnumerator()
    {
      return MyList.GetEnumerator();
    }

或者你可以自己实现一个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();
            }
        }
    }
}

返回数组

return MyList.ToArray();

或者如果你想返回List,为什么不直接

呢?
return MyList;