假设您有以下内容:
public Form1()
{
InitializeComponent();
collection.CollectionChanged += new NotifyCollectionChangedEventHandler(collection_CollectionChanged);
}
并且假设收集的寿命比这个表单长,那么上面的事件处理程序将阻止表单被垃圾收集。假设您每次显示时都在创建一个新表单,您可以在表单的 FormClosed 事件中取消订阅,如下所示:
public Form1()
{
InitializeComponent();
collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(collection_CollectionChanged);
FormClosed += new FormClosedEventHandler(Form1_FormClosed);
}
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
collection.CollectionChanged -= new System.Collections.Specialized.NotifyCollectionChangedEventHandler(collection_CollectionChanged);
}