foreach自动调用Dispose吗? [英] Does foreach automatically call Dispose?

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

问题描述

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

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

http://msdn.microsoft.com/zh-cn/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天全站免登陆