IDisposable 接口实现模板

/// <summary>
    /// Demo how to implement interface IDisposable
    /// </summary>
    class DemoClass:IDisposable
    {
        public DemoClass()
        {
           
        }

        //标示当前对象是否被Dispose过
        private bool disposed = false;


        /// <summary>
        /// 实现IDisposable中定义的接口方法
        /// </summary>
        public void Dispose()
        {
            
            //It must be ture;
            Dispose(true);
            //通知垃圾回收机制不再调用终结器(析构函数)
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Close函数为了更好滴符合其他语言规范
        /// </summary>
        public void Close()
        {
            Dispose();
        }

        /// <summary>
        /// 防止程序猿忘记显示调用Dispose
        /// </summary>
        ~DemoClass()
        {
            
            //It must be false
            Dispose(false);
        }

        private void DisposeUnmanagedSource()
        {
            //Clean Unmanaged Resouce
            

        }

        protected virtual void Dispose(bool disposing)
        {
            
            if (disposed)
            {
                return;
            }
            if (disposing)
            {
                DisposeUnmanagedSource();
            }
            disposed = true;
        }
    }

 

posted on 2012-10-30 19:37  笑东风  阅读(258)  评论(0编辑  收藏  举报

导航