C# how to implement Dispose method

前端 未结 3 640
温柔的废话
温柔的废话 2021-01-30 13:51

I need some advice on the implementation of the Dispose method.

In our application the user designs their own UI. I have a preview window that shows what t

3条回答
  •  日久生厌
    2021-01-30 14:21

    Question 1: Implement IDisposable as well, using the following pattern:

    public class MyClass : IDisposable
    {
        bool disposed;
    
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    //dispose managed resources
                }
            }
            //dispose unmanaged resources
            disposed = true;
        }
    
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
    

    Question 2: What Microsoft means is that a derived class calls dispose on it's parent class. The owner of the instance only calls Dispose on the most derived type.

    An (shortened) example:

    class Parent : IDisposable 
    {
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    //dispose managed resources
                }
            }
            //dispose unmanaged resources
            disposed = true;
        }
    
    }
    class Child : Parent, IDisposable 
    { 
        protected override void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    //dispose managed resources
                }
                base.Dispose(disposing);
            }
            //dispose unmanaged resources
            disposed = true;
        }
    
    }
    class Owner:IDisposable
    {
        Child child = new Child();
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    if(child!=null)
                    {
                        child.Dispose();
                    }
                }
            }
            //dispose unmanaged ressources
            disposed = true;
        }
    }
    

    The owner only calls Dispose on the Child, but not on the Parent. The Child is responsible for calling Dispose on the Parent.

提交回复
热议问题