在C#中处置嵌套集合

时间:2012-01-24 00:14:09

标签: c# .net dispose filehandle

我有一组对象,每个对象都有一个对象集合(从下面的代码可以看出这些对象)。我想创建一个“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),但它正在使用中,目前无法删除。

2 个答案:

答案 0 :(得分:1)

为什么不在列举后清除列表?

// 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

那应该做你正在尝试的事情。

答案 1 :(得分:0)

您无需将列表中的项目移至Dispose。只需遍历列表,依次处理每个列表。如果要清空集合,请在循环完成后执行此操作。