只是一个简单的问题。首先,让我验证一下函数指针的正确含义。在C#的情况下,函数指针基本上只是一个事件函数我对吗?
第二,请考虑以下代码段:
public FormAnimator(Form form)
{
this.m_Form = form;
this.m_Form.Load += new EventHandler(m_Form_Load);
this.m_Form.VisibleChanged += new EventHandler(m_Form_VisibleChanged);
this.m_Form.Closing += new CancelEventHandler(m_Form_Closing);
}
其中m_Form是类型为
的私有变量 //The form to be animated.
private Form m_Form;
下面是如何实例化类:
public partial class toastform : Form
{
public toastform(skImage ic) : this() {
//Attach this form to the Formanimator.
//The FormAnimator now has a reference to this toastform.
//When the load() of this form is invoked, the Form animator intercepts it and displays the form.
this.m_Animator = new FormAnimator(this, FormAnimator.AnimationMethod.Slide, FormAnimator.AnimationDirection.Up, 400);
}
所以当我创建一个新的toastform(使用something = new toastform();)并调用Show()时,show方法应该是来自形式animator的方法。现在,当toastform关闭时,我如何确保FormAnimator对象也被破坏...如果有人能够解释正在发生的事情的完整故事,我会很感激。我的意思是...做toastform类,而formanimator类都指向同一个对象,当我说形式动画师“拦截”taostform的事件等时,我的术语是正确的。
感谢
tldr:我只需要知道是否需要手动删除Formanimator类中事件的处理程序。
答案 0 :(得分:3)
在Dispose
函数中,您应该分离函数引用。
protected override Dispose(bool disposing)
{
....
this.m_Form.Load -= new EventHandler(m_Form_Load);
this.m_Form.VisibleChanged -= new EventHandler(m_Form_VisibleChanged);
this.m_Form.Closing -= new CancelEventHandler(m_Form_Closing);
}
或者,您可以使用弱引用。
以下是关于弱引用的非常非常的好文章:
http://diditwith.net/PermaLink,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx
答案 1 :(得分:1)
你需要。垃圾收集在一些不可预测的时间运行。未引用的对象将被垃圾收集,但您永远不知道何时。