What is the simplest IDisposable pattern in c#?

This question already has an answer here:

  • Proper use of the IDisposable interface 18 answers

  • You almost had it, because your class is not sealed someone could derive from your class and that derived class could also need to dispose a object. Make your class sealed and your current implementation is fine.

    public sealed class ManagedResourceClient : IDisposable
    {
        private ITheManagedResource _myManagedResource = new TheManagedResource()
    
        public void Dispose()
        {
            if ( _myManagedResource != null )
            {
                _myManagedResource.Dispose();
                _myManagedResource = null;
            }
        } 
    }
    

    If you want to learn more about disposing (and why the stock example with a finializer Microsoft gives is actually a bad example) see this really good article by Stepen Cleary: "IDisposable: What Your Mother Never Told You About Resource Deallocation"

    链接地址: http://www.djcxy.com/p/54484.html

    上一篇: 实现IDisposable

    下一篇: 什么是C#中最简单的IDisposable模式?