在foreach期间处置

在这个问题中: 通过DirectoryEntry或任何对象层次结构循环 – C#

遍历LDAP树的建议答案是

DirectoryEntry root = new DirectoryEntry(someDN); DoSomething(root); function DoSomething(DirectoryEntry de){ // Do some work here against the directory entry if (de.Children != null) { foreach (DirectoryEntry child in de.Children) { DoSomething(child); } } } 

我的问题是:你是否需要在每次迭代结束时对每个孩子调用Dispose()? 或者foreach循环是否会处理对Dispose()的必要调用? 或者它们在foreach循环中根本不是必需的(因为循环可能会重新使用本来想要Dispose()的资源)

是的,你需要给每个孩子打电话。 当您调用DirectoryEntry Children属性时,它实际上会创建新的DirectoryEntries实例。 当您枚举该实例时,它会逐个拉出子条目(并非一次全部拉出),并且它不会Dispose它们(也不会重复使用它们)。 由于DirectoryEntry基本上是COM对象 – 处理它(它拥有非托管资源)非常重要。 所以正确的方法是这样的:

 function DoSomething(DirectoryEntry de){ // Do some work here against the directory entry if (de.Children != null) { foreach (DirectoryEntry child in de.Children) { using (child) { DoSomething(child); } } } }