Does foreach automatically call Dispose?

强颜欢笑 提交于 2019-12-17 07:23:08

问题


In C#, Does foreach automatically call Dispose on any object implementing IDisposable?

http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx seems to indicate that it does:

*Otherwise, the collection expression is of a type that implements System.IEnumerable, and the expansion of the foreach statement is: Copy

IEnumerator enumerator = 
        ((System.Collections.IEnumerable)(collection)).GetEnumerator();
try {
   while (enumerator.MoveNext()) {
      ElementType element = (ElementType)enumerator.Current;
      statement;
   }
}
finally {
   IDisposable disposable = enumerator as System.IDisposable;
   if (disposable != null) disposable.Dispose();
}

回答1:


Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.




回答2:


This question / answer is poorly worded.

It is not clear if the question asked is:

Q: "Does foreach dispose objects returned by the enumerator before moving to the next?"

A: The answer is of course, NO. It does nothing except provide a convenient way to run some code once for each object in an enumeration.

Or whether it means:

Q: "Under the hood, foreach uses an enumerable object. Does this get disposed after the call to foreach, even if there's an exception in the iterator block?"

A: The answer is (still fairly obviously) YES! Since the syntax does not provide you access to the enumerator, it has the responsibility to dispose it.

The answer to the second question is where the confusion arises, since people have heard that foreach expands to a while block with a try/finally block. The purpose of that finally is to ensure that the enumerator is disposed if it implements IDisposable.

In case you need to see it for yourself: See it in action here

Hope this helps clarify! ;)



来源:https://stackoverflow.com/questions/4982396/does-foreach-automatically-call-dispose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!