What's the point of overriding Dispose(bool disposing) in .NET?

后端 未结 8 1008
故里飘歌
故里飘歌 2021-01-30 10:38

If I write a class in C# that implements IDisposable, why isn\'t is sufficient for me to simply implement

public void Dispose(){ ... } 

to han

8条回答
  •  执念已碎
    2021-01-30 11:08

    The full pattern including a finalizer, introduction of a new virtual method and "sealing" of the original dispose method is very general purpose, covering all bases.

    Unless you have direct handles on unmanaged resources (which should be almost never) you don't need a finalizer.

    If you seal your class (and my views on sealing classes wherever possible are probably well known by now - design for inheritance or prohibit it) there's no point in introducing a virtual method.

    I can't remember the last time I implemented IDisposable in a "complicated" way vs doing it in the most obvious way, e.g.

    public void Dispose()
    {
        somethingElse.Dispose();
    }
    

    One thing to note is that if you're going for really robust code, you should make sure that you don't try to do anything after you've been disposed, and throw ObjectDisposedException where appropriate. That's good advice for class libraries which will be used by developers all over the world, but it's a lot of work for very little gain if this is just going to be a class used within your own workspace.

提交回复
热议问题