How to handle an “infinite” IEnumerable?

前端 未结 5 1830
醉梦人生
醉梦人生 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 18:02

    Yes, your code will always work without infinite looping. Someone might come along though later and mess things up. Suppose they want to do:

    var q = Numbers().ToList();
    

    Then, you're hosed! Many "aggregate" functions will kill you, like Max().

提交回复
热议问题