在 foreach 期间处理
- 作者: 最凉丨不过人心
- 来源: 51数据库
- 2022-10-28
问题描述
在这个问题中:遍历 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.当您调用 DirectoryEntry 的 Children 属性时,它实际上会创建新的 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);
}
}
}
}
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
