开发者

How should I handle resources created by XmlSerializer?

Let's say I have a class:

class Class1
{
    public List<Class2> Classes;
}

that I deserialize with XmlSerializer and Class2 creates some stuff that I should Dispose. Should I dispose everything myself or is that going to be don开发者_开发问答e automatically?


Rule of thumb: if you're using a class that implements IDisposable, you should make sure to call the Dispose() method (you can use a using block for this). If the class doesn't implement IDisposable than .NET will take care of it for you.

For your own classes, you should implement IDisposable if your class has a member variable that either implements IDisposable or is unmanaged.


If Class2 has some stuff it should dispose of then this also means that Class1 has some stuff to dispose of, the Class2s. The safest thing to do would be to have Class1 also implement IDisposable and make its dispose method tidy up the Class2s.

class Class1 : IDisposable
{
    public List<Class2> Classes;

    public void Dispose()
    {
        foreach(Class2 c in Classes
        {
            c.Dispose();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜