在C#中如何覆盖finalize()方法? [英] In C# how to override the Finalize() method?

查看:307
本文介绍了在C#中如何覆盖finalize()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下功能,给予编译错误不要覆盖object.Finalize,而是提供了一个析构函数。<​​/ p>

 保护覆盖无效敲定()
{
this.Dispose();
base.Finalize();
}


解决方案

终结方法被称为〜名称()与你的类名称替换名称。



C#编译器将生成此终结。



但请注意:




  1. 仅使用finaliser如果你真的需要它:你的类型的直接的包含本地资源(一种合成的包装只是使用了Dispose模式)。

  2. 考虑专业的SafeHandle 而不是写你自己的。

  3. 实施Dispose模式,以允许呼叫者快速释放资源。

  4. 确保双方的处置,终结是幂&MDASH;他们可以安全地多次调用



例如

  MyClass类:IDisposable的{
私人的IntPtr SomeNativeResource;

〜MyClass的(){
的Dispose(假);
}

公共无效的Dispose(){
的Dispose(真);
}

受保护的虚拟无效的Dispose(BOOL处置){
如果(处置){
//处理任何可支配领域这里
GC.SuppressFinalize(这个);
}
ReleaseNativeResource();
}
}



子类可以覆盖的Dispose(布尔)来增加他们添加任何附加字段并调用基实施



编辑:。要添加什么时候完成的例子和说明


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

protected override void Finalize()
{           
    this.Dispose();
    base.Finalize();
}

解决方案

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.

这篇关于在C#中如何覆盖finalize()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆