【发布时间】:2017-06-08 07:41:19
【问题描述】:
我的对象有点问题... 我有一个对象,里面有一个委托,它在构造函数中订阅。 当我销毁这个对象时,调用列表仍然告诉我它有一个订阅者。当我再次创建这个对象时,我找到了两个订阅者(我已经销毁的旧订阅者和新订阅者)。 我该如何解决这个问题并干净地删除列表中的订阅者?
这里是测试代码:(里面有两个按钮来销毁和创建对象)
public partial class Form1 : Form
{
testdelegate thisdelegatetest;
public Form1()
{
InitializeComponent();
thisdelegatetest = new testdelegate();//create object
Timer mytimer = new Timer();//timer to see something BEGIN
mytimer.Interval = 1000;
mytimer.Tick += new EventHandler(mytimer_Tick);
mytimer.Start();//timer to see something END
}
protected void mytimer_Tick(object sender, EventArgs e)
{//each 1second look at the list invocation
lb_IndelList.Text = "actual subscribers : " + testdelegate.dl_myfunctionthatcopy.GetInvocationList().Count().ToString();
}
private void DestroyObject_Click(object sender, EventArgs e)
{//destroy object
/*edit*/
thisdelegatetest.Delete();
thisdelegatetest = null;//dereferencing for GC
/*edit*/
}
private void CreateObject_Click(object sender, EventArgs e)
{//create object
thisdelegatetest = new testdelegate();
}
}
public class testdelegate
{
public delegate void del_copysomething(int newvaluetocopy);
internal static del_copysomething dl_myfunctionthatcopy;
public int valueforallobject = 0;
public testdelegate()//ctor
{
dl_myfunctionthatcopy += new del_copysomething(copythisint);
}
/*edit*/
public void Delete()
{
dl_myfunctionthatcopy -= new del_copysomething(copythisint);
}
/*edit*/
private void copythisint(int newvalue)
{
valueforallobject = newvalue;
}
}
感谢您的帮助。
【问题讨论】:
-
将变量设置为
null不会“销毁”一个对象。无论您对 C# 中对象如何工作的心智模型是什么,都是错误的。 -
您能解释一下您所做的修改吗?
-
请不要编辑您的问题,使其不再显示问题,因此没有意义。
-
编辑的内容在 /*edit*/ 引号之间。我认为很清楚。
标签: c# object delegates destroy