157 recommendations for writing high-quality code to improve C # programs-Recommendation 49: A protected virtual method should be extracted in Dispose mode

Source: Internet
Author: User

Recommendation 49: A protected virtual method should be extracted in Dispose mode

In the standard dispose mode, the Dispose method of the real IDisposable interface does not do the actual cleanup work, it actually calls the following virtual method with the bool parameter and is protected:

 /// <SUMMARY>  ///  non-sealed class decoration with protected virtual  ///   sealed class decoration with private  /// </summary>  /// <param name= " Disposing "></PARAM>  protected  virtual  void  Dispose (bool   disposing) {
//omit code }

The reason for providing such a protected virtual method is to consider the case where the type is inherited by another type. If a type has a subclass, the subclass might implement its own dispose pattern. A protected virtual method is used to alert subclasses that the cleanup work of the parent class must be noticed in its own cleanup method, that is, the subclass needs to call base in its own release method. Dispose method.

     Public classDerivedsampleclass:sampleclass {//unmanaged Resources for subclasses        PrivateIntPtr Derivednativeresource = Marshal.allochglobal ( -); //managed resources for subclasses        PrivateAnotherresource Derivedmanagedresource =NewAnotherresource (); //define your own identity variables that are released        Private BOOLderiveddisposed =false; /// <summary>        ///overriding the parent class Dispose method/// </summary>        /// <param name= "disposing" ></param>        protected Override voidDispose (BOOLdisposing) {            if(deriveddisposed) {return; }            if(disposing) {//clean up Managed resources                if(Derivedmanagedresource! =NULL) {derivedmanagedresource.dispose (); Derivedmanagedresource=NULL; }            }            //Cleanup of unmanaged Resources            if(Derivednativeresource! =IntPtr.Zero) {Marshal.freehglobal (Derivednativeresource); Derivednativeresource=IntPtr.Zero; }            //calling the cleanup code of the parent class            Base.            Dispose (disposing); //let the type know that they have been releasedderiveddisposed =true; }    }     Public classsampleclass:idisposable {//Demo Creating an unmanaged resource        PrivateIntPtr Nativeresource = Marshal.allochglobal ( -); //Demo Creating a managed resource        PrivateAnotherresource Managedresource =NewAnotherresource (); Private BOOLdisposed =false; /// <summary>        ///implementing the Dispose method in IDisposable/// </summary>         Public voidDispose () {//must be TrueDispose (true); //notifies the garbage collection mechanism not to call finalizers (destructors)Gc. SuppressFinalize ( This); }        /// <summary>        ///is not necessary, providing a close method is just for more compliance with other languages (such as///Specification for C + +)/// </summary>         Public voidClose () {Dispose (); }        /// <summary>        ///must prevent programmers from forgetting to explicitly call the Dispose method/// </summary>~SampleClass () {//must be falseDispose (false); }        /// <summary>        ///protected virtual for non-sealed class modification///Seal class decoration with private/// </summary>        /// <param name= "disposing" ></param>        protected Virtual voidDispose (BOOLdisposing) {            if(disposed) {return; }            if(disposing) {//clean up Managed resources                if(Managedresource! =NULL) {managedresource.dispose (); Managedresource=NULL; }            }            //Cleanup of unmanaged Resources            if(Nativeresource! =IntPtr.Zero) {Marshal.freehglobal (Nativeresource); Nativeresource=IntPtr.Zero; }            //let the type know that they have been releaseddisposed =true; }         Public voidSamplepublicmethod () {if(disposed) {Throw NewObjectDisposedException ("SampleClass","SampleClass is disposed"); }            //omitted        }    }    classanotherresource:idisposable { Public voidDispose () {}}


If you do not provide this protected virtual method for your class, it is likely that you will let the developer design the subclass by ignoring the cleanup work of the parent class. Therefore, you provide a protected virtual method in the type of Dispose mode.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs-Recommendation 49: A protected virtual method should be extracted in Dispose mode

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.