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();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…