How to handle an “infinite” IEnumerable?

前端 未结 5 1702
醉梦人生
醉梦人生 2021-02-01 17:11

A trivial example of an \"infinite\" IEnumerable would be

IEnumerable Numbers() {
  int i=0;
  while(true) {
    yield return unchecked(i++);
  }
}
         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 17:52

    Yes, you are guaranteed that the code above will be executed lazily. While it looks (in your code) like you'd loop forever, your code actually produces something like this:

    IEnumerable Numbers()
    {
        return new PrivateNumbersEnumerable();
    }
    
    private class PrivateNumbersEnumerable : IEnumerable
    {
        public IEnumerator GetEnumerator() 
        { 
            return new PrivateNumbersEnumerator(); 
        }
    }
    
    private class PrivateNumbersEnumerator : IEnumerator
    {
        private int i;
    
        public bool MoveNext() { i++; return true; }   
    
        public int Current
        {
            get { return i; }
        }
    }
    

    (This obviously isn't exactly what will be generated, since this is pretty specific to your code, but it's nonetheless similar and should show you why it's going to be lazily evaluated).

提交回复
热议问题