正在处理C#中的嵌套集合
本文关键字:嵌套 集合 处理 | 更新日期: 2023-09-27 18:21:07
我有一组对象,每个对象中都有一个对象集合(从下面的代码中可以明显看出)。我想创建一个"dispose"方法,去掉所有附件,然后去掉部分,这样我就可以删除相关文件。这些物体被用在不同的地方,所以据我所见,"使用"方法并不合适。以下操作失败(可以理解),因为集合已被修改。
// Find files and get names.
foreach (DocumentSection s in this.sections)
{
foreach (EmailAttachment a in s.SectionAttachments)
{
// Get file location, then clear attachment to release file handle.
filesToDelete.Add(a.TempAttachmentFileLoc);
s.SectionAttachments.Remove(a);
a = null;
}
this.sections.Remove(s);
s = null;
}
我之所以这么做,是因为我想在使用后删除临时文件(TempAttachmentFileLoc),但它正在使用中,目前无法删除。
为什么不在枚举后清除列表?
// Find files and get names.
foreach (DocumentSection s in this.sections)
{
foreach (EmailAttachment a in s.SectionAttachments)
{
// Get file location, then clear attachment to release file handle.
filesToDelete.Add(a.TempAttachmentFileLoc);
//s.SectionAttachments.Remove(a); // removed this!
//a = null;
}
s.SessionAttachments.Clear(); // Added this
//this.sections.Remove(s); // Removed this
//s = null;
}
this.sections.Clear(); // Added this
这应该是你正在尝试的。
您不需要将列表中的项目删除到Dispose
中。只需迭代您的列表,然后依次处理每个列表。如果要清空集合,请在循环完成后执行此操作。