使用析构函数分离事件

Using destructors to detach events

在项目中注意到这段代码:

所以有一个自定义的文本框:

public sealed class CoolTextBox : TextBox
{
    ...
    public CoolTextBox()
    {
        this.DefaultStyleKey = typeof(CoolTextBox);
        this.TextChanged += this.CoolTextBox_TextChanged;
    }

    ~CoolTextBox()
    {
        this.TextChanged -= this.CoolTextBox_TextChanged;
    }
    ...
}

我从来没有写过这种类型的结构。但据我所知,来自 google 的信息表明你不应该相信析构函数,因为它们可以随时调用。

我应该只删除析构函数吗?

终结器只能用于清理非托管资源。它们可以按任何顺序调用,并且有最长执行时间。

如果您有任何非托管资源,请使用 Dispose pattern

如果您没有任何非托管资源,请实施 IDisposable

您应该清理的事件是您要处理的 class 注册到另一个对象上的事件的地方,该对象的寿命会更长。

如果您可以完全避免使用 event,那就更好了,因为忘记注销处理程序会阻止垃圾回收。