销毁对象不会从调用列表中删除委托

destroying object doesn't remove delegate from invocation list

我的对象有点问题... 我有一个对象,其中有一个委托,它在构造函数中订阅了该委托。 当我销毁这个对象时,调用列表仍然告诉我它有一个订阅者。当我再次创建这个对象时,我发现有两个订阅者(我已经销毁的旧订阅者和新订阅者)。 我怎样才能解决这个问题并彻底删除列表中的订阅者?

这是测试代码:(两个按钮用于销毁和创建内部对象)

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;
    }
}

感谢您的帮助。

private void DestroyObject_Click(object sender, EventArgs e)
{//destroy object
    thisdelegatetest = null;
}

这并没有真正破坏对象。对象被垃圾收集器"destroyed"(释放)。

事实上,它不能被标记为可收集的,因为static委托仍然引用它。因此,永远不会调用析构函数。您已手动删除订阅者,例如通过 public 方法。

既然不能手动调用析构函数,为什么不实现IDisposable接口,在Dispose方法中执行注销呢?=!

public class testdelegate : IDisposable
{
    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);
    }
    private void copythisint(int newvalue)
    {
        valueforallobject = newvalue;
        Console.WriteLine("Copied");
    }

    public void Dispose()
    {
        dl_myfunctionthatcopy -= new del_copysomething(copythisint);
        GC.SuppressFinalize(this);
    }
}

DestroyObject_Click 方法中,您只需调用 Dispose 方法:

private void DestroyObject_Click(object sender, EventArgs e)
{   //call Dispose destroy object
    thisdelegatetest.Dispose();
}