在 foreach 期间处理

时间:2023-01-01
本文介绍了在 foreach 期间处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在这个问题中:遍历 DirectoryEntry 或任何对象层次结构 - C#

遍历 LDAP 树的建议答案是

The suggested answer for traversing an LDAP tree is to

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() 的资源)

My Question is: Do you need to call Dispose() on each child at the end of each iteration? or will the foreach-loop handle the necessary calls to Dispose()? or are they simply not necessary in a foreach-loop (because perhaps the loop re-uses the resources one would otherwise want to Dispose())

推荐答案

是的,您需要对每个孩子调用 Dispose.当您调用 DirectoryEntryChildren 属性时,它实际上会创建新的 DirectoryEntries 实例.当您枚举该实例时,它会一一拉取子条目(不是一次全部提取),并且不会 Dispose 它们(也不会重用它们).由于 DirectoryEntry 基本上是 COM 对象 - 处理它非常重要(它持有非托管资源).所以正确的方法是这样的:

Yes you need to call Dispose on every child. When you call Children property of DirectoryEntry, it actually creates new DirectoryEntries instance. When you enumerate over that instance, it pulls child entries one by one (not all of them at once), and it will not Dispose them (nor anything will reuse them). Since DirectoryEntry is basically COM object - it's quite important to dispose it (it hold unmanaged resources). So correct way is something like this:

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

这篇关于在 foreach 期间处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:Active Directory 和 PrincipalPermission 下一篇:如何在 C# 中从 Active Directory 获取 System.__ComObject 值

相关文章

最新文章