Using IEnumerable without foreach loop

后端 未结 7 1042

I\'ve gotta be missing something simple here.

Take the following code:

public IEnumerable getInt(){
  for(int i = 0; i < 10; i++){
   y         


        
7条回答
  •  悲&欢浪女
    2020-11-30 03:44

    It's important to mention that the duty of the foreach loop is to dispose the enumerator if the instance implements IDisposable. In other words, foreach should be replaced with something like:

    var enumerator = enumerable.GetEnumerator();
    
    try
    {
        while (enumerator.MoveNext())
        {
            var item = enumerator.Current;
            // do stuff
        }
    }
    finally
    {
        var disposable = enumerator as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
    

提交回复
热议问题