如何处置XmlDocument

Ama*_*mal 5 .net c# xmldocument

我正在使用流创建 XmlDocument,并在 XmlDocument 中进行一些更改,并将 XmlDocument 保存到流本身。

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileStream);

////
////

////  
xmlDocument.Save(fileStream);
//how to dispose the created XmlDocument object.
Run Code Online (Sandbox Code Playgroud)

现在我如何销毁 XmlDocument 对象?

par*_*ter 5

该类XmlDocument没有实现IDisposable,因此无法强制它随意释放其资源。如果您需要释放该内存,唯一的方法就是xmlDocument = null;垃圾收集将处理其余的事情。


Gyö*_*zeg 5

首先,您不应该重复使用这样的流。您真的想长期保持外部资源开放吗?您会在重新保存 xml 之前寻找流吗?如果流比之前短,您会在保存后截断流吗?

如果出于某种合理的原因,答案是正确的,则使您的 XML 操纵器类成为一次性的:

public class MyXmlManipulator : IDisposable
{
    private FileStream fileStream;

    // ...

    public void ManipulateXml()
    {
        // your original codes here...
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~MyXmlManipulator()
    {
        Dispose(false);
    }

    protected virtual Dispose(bool disposing)
    {
        fileStream.Close();
        // etc...
    }
}
Run Code Online (Sandbox Code Playgroud)

但基本上我会说不要保留对文件流的长期引用并像这样重新使用它。相反,仅在本地使用流并尽快处理它们。您在全局范围内可能需要的只是一个文件名。

public class MyXmlManipulator
{
    private string fileName;

    // ...

    public void ManipulateXml()
    {
        XmlDocument xmlDocument = new XmlDocument();
        using (var fs = new FileStream(fileName, FileMode.Open)
        {
            xmlDocument.Load(fs);
        }

        // ...

        // FileMode.Create will overwrite the file. No seek and truncate is needed.
        using (var fs = new FileStream(fileName, FileMode.Create)
        {
            xmlDocument.Save(fs);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

XmlDocument无法处置,因为它没有实现IDisposable。真正的问题是你为什么要摧毁这个物体?

如果您不保留对该对象的引用,垃圾收集器将删除它。

如果您希望该过程更快,您唯一能做的就是按照 Fildor 所说的那样:将对象设置为null