【转】编写高质量代码改善C#程序的157个建议——建议51:具有可释放字段的类型或拥有本机资源的类型应该是可释放的

建议51:具有可释放字段的类型或拥有本机资源的类型应该是可释放的

在建议50中,我们将C#中的类型分为:普通类型和继承了IDisposable接口的非普通类型。非普通类型除了包含那些托管资源的类型外,本身还包含一个非普通类型的字段。

在标准的Dispose模式中,我们对非普通类型举了一个例子:一个非普通类型AnotherResource。由于AnotherResource是一个非普通类型,所以如果有一个类型,它组合了AnotherResource,那么他就应该继承IDisposable接口:

    class AnotherSampleClass : IDisposable
    {
        private AnotherResource managedResource = new AnotherResource();
        private bool disposed = false;

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

        ~AnotherSampleClass()
        {
            Dispose(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            if (disposing)
            {
                // 清理托管资源
                if (managedResource != null)
                {
                    managedResource.Dispose();
                    managedResource = null;
                }
            }
            disposed = true;
        }

        public void SamplePublicMethod()
        {
            if (disposed)
            {
                throw new ObjectDisposedException("AnotherSampleClass", "AnotherSampleClass is disposed");
            }
            //省略
        }
    }

类型AnotherSampleClass虽然没有包含任何显式的非托管资源,但是由于它本身包含了一个非普通类型,所以我们仍旧必须为它实现一个标准的Dispose模式。

除此之外,类型拥有本机资源(即非托管资源),它也应该继承IDisposable接口。

转自:《编写高质量代码改善C#程序的157个建议》陆敏技