In C# how to override the Finalize() method?

前端 未结 3 938
自闭症患者
自闭症患者 2021-01-12 04:38

Following function giving compilation error \"Do not override object.Finalize. Instead, provide a destructor.\"

protected override void Finalize()
{                  


        
3条回答
  •  被撕碎了的回忆
    2021-01-12 05:07

    The finalizer method is called ~name() replacing "name" with your class name.

    The C# compiler will generate the finalizer from this.

    But note:

    1. Only use a finaliser if you really need it: your type directly contains a native resource (a type composing a wrapper just uses the Dispose pattern).
    2. Consider specialising SafeHandle rather than writing your own.
    3. Implement the dispose pattern to allow callers to release the resource quickly.
    4. Ensure both your Dispose and Finalizer are idempotent—they can be safely called multiple times.

    e.g.

    class MyClass : IDisposable {
      private IntPtr SomeNativeResource;
    
      ~MyClass() {
        Dispose(false);
      }
    
      public void Dispose() {
        Dispose(true);
      }
    
      protected virtual void Dispose(bool disposing) {
        if (disposing) {
          // Dispose any disposable fields here
          GC.SuppressFinalize(this);
        }
        ReleaseNativeResource();
      }
    }
    

    Subclasses can override Dispose(bool) to add any addition fields they add and call the base implementation.

    EDITED: To add example and notes about when to finalise.

提交回复
热议问题