foreach 是否会自动调用 Dispose? [英] Does foreach automatically call Dispose?

查看:36
本文介绍了foreach 是否会自动调用 Dispose?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,foreach 是否会在任何实现 IDisposable 的对象上自动调用 Dispose?

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

http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx 似乎表明它确实如此:

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

*否则,集合表达式是实现System.IEnumerable的类型,foreach语句的展开为:复制

*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();
}

推荐答案

是的,foreach 会在枚举器上调用 Dispose(),如果它实现了 IDisposable.

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

这篇关于foreach 是否会自动调用 Dispose?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆